使用CharacterController来控制物体向朝向方向移动的代码
时间: 2024-02-05 13:12:13 浏览: 21
使用CharacterController控制物体移动需要用到以下代码:
```csharp
using UnityEngine;
public class CharacterMovement : MonoBehaviour
{
public float speed = 5f;
private CharacterController controller;
void Start()
{
controller = GetComponent<CharacterController>();
}
void Update()
{
// 获取输入的方向
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
// 计算朝向
Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
// 如果有方向输入,则移动
if (direction.magnitude >= 0.1f)
{
// 计算角度
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + Camera.main.transform.eulerAngles.y;
Vector3 moveDirection = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
// 移动
controller.Move(moveDirection.normalized * speed * Time.deltaTime);
}
}
}
```
这段代码中,首先获取了CharacterController组件并在Update函数中获取了输入的方向,然后计算朝向并移动。其中,计算角度的步骤是为了让物体面向移动的方向。