unity人物旋转移动代码
时间: 2023-09-24 16:09:50 浏览: 46
以下是一个简单的Unity人物旋转移动代码示例:
```csharp
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float moveSpeed = 5f;
public float rotationSpeed = 100f;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(horizontal, 0f, vertical) * moveSpeed * Time.deltaTime;
rb.MovePosition(rb.position + transform.TransformDirection(movement));
if (movement != Vector3.zero)
{
Quaternion newRotation = Quaternion.LookRotation(movement);
rb.MoveRotation(Quaternion.RotateTowards(rb.rotation, newRotation, rotationSpeed * Time.deltaTime));
}
}
}
```
在这个示例代码中,我们通过获取输入的水平和垂直轴向来控制人物的移动。我们使用 Rigidbody 的 MovePosition 方法来更新人物的位置,使用 LookRotation 方法计算新的旋转方向,然后使用 RotateTowards 方法逐步将人物的旋转角度逼近新的旋转方向。
需要注意的是,这只是一个基本的示例代码,实际应用中需要根据具体需求进行调整和优化。