Unity游戏基础-4:人物移动、相机移动与UI事件处理代码详解
人物移动的实现
在Unity中,人物移动通常通过脚本控制角色对象的Transform组件实现。以下是一个基于输入控制的简单人物移动脚本示例:
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 5f;
public float rotationSpeed = 180f;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(horizontalInput, 0f, verticalInput) * moveSpeed * Time.deltaTime;
transform.Translate(movement, Space.World);
if (movement != Vector3.zero)
{
Quaternion toRotation = Quaternion.LookRotation(movement, Vector3.up);
transform.rotation = Quaternion.RotateTowards(transform.rotation, toRotation, rotationSpeed * Time.deltaTime);
}
}
}
这段代码实现了基本的WASD键控制角色移动和转向功能。moveSpeed控制移动速度,rotationSpeed控制旋转速度。GetAxis方法获取输入设备的输入值,范围在-1到1之间。Time.deltaTime确保移动速度不受帧率影响。
相机跟随的实现
第三人称相机跟随是许多游戏的基本需求。以下代码实现了平滑跟随角色的相机控制:
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
public Transform target;
public float distance = 5f;
public float height = 2f;
public float damping = 5f;
public float rotationDamping = 10f;
void LateUpdate()
{
float wantedRotationAngle = target.eulerAngles.y;
float wantedHeight = target.position.y + height;
float currentRotationAngle = transform.eulerAngles.y;
float currentHeight = transform.position.y;
currentRotationAngle = Mathf.LerpAngle(currentRotationAngle, wanted
49

被折叠的 条评论
为什么被折叠?



