Unity第三人称移动
时间: 2023-07-09 13:51:02 浏览: 127
以下是一个简单的第三人称移动示例,包括人物的移动、转向和动画播放:
```csharp
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ThirdPersonMovement : MonoBehaviour
{
public CharacterController controller;
public Transform cam;
public Animator animator;
public float speed = 6f;
public float turnSmoothTime = 0.1f;
float turnSmoothVelocity;
// Update is called once per frame
void Update()
{
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
if (direction.magnitude >= 0.1f)
{
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
transform.rotation = Quaternion.Euler(0f, angle, 0f);
Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
controller.Move(moveDir.normalized * speed * Time.deltaTime);
animator.SetBool("isWalking", true);
}
else
{
animator.SetBool("isWalking", false);
}
}
}
```
其中,CharacterController是Unity提供的用于角色控制的组件,cam是摄像机的Transform组件,animator是角色的动画控制器。在Update函数中,首先获取水平和垂直方向上的输入值,然后计算出移动方向并进行平滑转向,最后移动角色并播放相应的动画。
阅读全文