如何让我的角色在移动时跳来跳去?
How can I make my character jump around when I move it?
我想做一个兔子第一人称模拟器,所以每次我的角色移动,跳跃我都需要做,我试着这样做:
if (Input.GetAxis("Vertical") > 0)
transform.position += new Vector3(transform.forward.x, 2f, transform.forward.z) * 2 * Time.deltaTime;
可以,但问题是当与另一个元素发生碰撞时,角色向上滑动并最终落在对象的顶部。
我留下一个 gif 来了解发生了什么:
在向前移动时使用 Raycast
检查是否撞到任何东西。如果它 returns 什么都没有那么你可以向前迈进。 (Take a look here)
using UnityEngine;
// C# example.
public class ExampleClass : MonoBehaviour
{
public float maxDetectionDistance = 1;
void Update()
{
RaycastHit hit;
var isHit = Physics.Raycast(transform.position, transform.forward, out hit, maxDetectionDistance);
// Does the ray intersect any objects excluding the player layer
if (!isHit)
{
if (Input.GetAxis("Vertical") > 0)
{
// your movement function
transform.position += new Vector3(transform.forward.x, 2f, transform.forward.z) * 2 * Time.deltaTime;
}
}
else
{
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);
Debug.Log("Did Hit");
}
}
}
我想做一个兔子第一人称模拟器,所以每次我的角色移动,跳跃我都需要做,我试着这样做:
if (Input.GetAxis("Vertical") > 0)
transform.position += new Vector3(transform.forward.x, 2f, transform.forward.z) * 2 * Time.deltaTime;
可以,但问题是当与另一个元素发生碰撞时,角色向上滑动并最终落在对象的顶部。
我留下一个 gif 来了解发生了什么:
在向前移动时使用 Raycast
检查是否撞到任何东西。如果它 returns 什么都没有那么你可以向前迈进。 (Take a look here)
using UnityEngine;
// C# example.
public class ExampleClass : MonoBehaviour
{
public float maxDetectionDistance = 1;
void Update()
{
RaycastHit hit;
var isHit = Physics.Raycast(transform.position, transform.forward, out hit, maxDetectionDistance);
// Does the ray intersect any objects excluding the player layer
if (!isHit)
{
if (Input.GetAxis("Vertical") > 0)
{
// your movement function
transform.position += new Vector3(transform.forward.x, 2f, transform.forward.z) * 2 * Time.deltaTime;
}
}
else
{
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);
Debug.Log("Did Hit");
}
}
}