如何在角色移动方向上面对角色,同时使其与任何曲面对齐



我想在曲面上移动我的玩家角色(人类(。但同时,角色应保持垂直于曲面法线,并且应面向移动方向,并可以处理碰撞(如果前方有墙,则无法穿过墙(。

我试图使父对象保持在法线之上,并将子对象的局部旋转更改为其父对象的运动方向。但到目前为止,它有几个局限性。这是我使用的代码:

[SerializeField] float raycastLength = 1f;
bool canPlayerMove = true;
public float speed = 2f;
public Vector3 offset; //object's position offset to ground / surface
public Quaternion childDirection;
private void Update()
{
float moveHorizontal = SimpleInput.GetAxis("Horizontal");
float moveVertical = SimpleInput.GetAxis("Vertical");
Ray ray = new Ray(transform.position, -transform.up);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo, raycastLength))
{
transform.rotation = Quaternion.LookRotation(Vector3.up, hitInfo.normal);
transform.position = hitInfo.point + offset;
Debug.DrawLine(ray.origin, hitInfo.point, Color.red);
}
if (canPlayerMove)
{
Vector3 movement = new Vector3(moveHorizontal, 0, moveVertical);
if (movement != Vector3.zero)
{
childDirection = Quaternion.Slerp(transform.GetChild(0).localRotation, Quaternion.LookRotation(movement), 0.15F);
transform.GetChild(0).localRotation = childDirection;
}
transform.Translate(movement * speed * Time.deltaTime, Space.Self); 
}
}

首先,为了不让你的玩家穿过墙壁,如果你想在墙壁上添加一个碰撞器,而不将其设置为触发器,你还需要在玩家身上安装一个刚体,这将在接下来的步骤中有所帮助。

其次,你需要使用以下代码来加速代码中的刚体:(如果你检查使用重力,它也会停留在你制作的地形上(

private Rigidbody rb;
private float speed = 7.5f;
private void Start()
{
//this gets the rigidbody on the gameObject the script is currently on.
rb = this.GetComponent<Rigidbody>();
}

private void Update()
{
float hor = Input.GetAxis("Horizontal");
float vert = Input.GetAxis("Vertical");

//this will move your player frame independent.
rb.MovePosition(this.transform.position + new Vector3(hor, 0, vert) * speed * 
Time.deltaTime);
}

还要确保你的播放器上有一个刚体,否则会出错。

相关内容

最新更新