Unity游戏基础-4:人物移动、相机移动与UI事件处理代码详解
人物移动实现
在Unity中实现人物移动通常依赖于输入系统和物理引擎。以下是基于Rigidbody的移动代码示例:
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public float moveSpeed = 5f;
public float rotationSpeed = 10f;
private Rigidbody rb;
private Vector3 movement;
void Start() {
rb = GetComponent<Rigidbody>();
}
void Update() {
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
movement = new Vector3(horizontal, 0, vertical).normalized;
}
void FixedUpdate() {
if (movement.magnitude > 0) {
rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
Quaternion targetRotation = Quaternion.LookRotation(movement);
rb.rotation = Quaternion.Slerp(rb.rotation, targetRotation, rotationSpeed * Time.fixedDeltaTime);
}
}
}
- 关键点:
Input.GetAxis获取键盘或手柄输入。Rigidbody.MovePosition避免直接修改Transform.position以保持物理合理性。Quaternion.Slerp实现平滑转向。
相机跟随逻辑
相机通常需要跟随玩家并保持一定偏移量。以下是一个第三人称相机脚本:
public class CameraFollow : MonoBehaviour {
public Transform target;
public Vector3 offset = new Vector3(0, 3, -5);
public float smoothSpeed = 0.125f;
void LateUpdate() {
Vector3 desiredPosition = target.position + offset;
Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
transform.position = smoothedPosition;
transform.LookAt(target);
}
}
- 关键点:
LateUpdate确保相机更新在玩家移动之后执行。Vector3.Lerp实现平滑过渡,避免镜头抖动。
UI事件处理
Unity的UI系统依赖EventSystem和UnityEngine.UI组件。以下是按钮点击事件的典型处理方式:
- 按钮绑定事件
using UnityEngine.UI;
public class UIManager : MonoBehaviour {
public Button startButton;
public Text statusText;
void Start() {
startButton.onClick.AddListener(OnStartButtonClick);
}
void OnStartButtonClick() {
statusText.text = "Game Started!";
Debug.Log("Button Clicked");
}
}
- 事件触发扩展
通过EventTrigger组件实现更复杂的交互(如悬停):
using UnityEngine.EventSystems;
public class HoverEffect : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler {
public Image buttonImage;
public void OnPointerEnter(PointerEventData eventData) {
buttonImage.color = Color.red;
}
public void OnPointerExit(PointerEventData eventData) {
buttonImage.color = Color.white;
}
}
性能与注意事项
- 人物移动:避免在
Update中直接调用物理操作,优先使用FixedUpdate。 - 相机跟随:调整
smoothSpeed防止镜头迟滞或过冲。 - UI事件:动态绑定时需在销毁前调用
RemoveListener防止内存泄漏。
通过结合输入控制、物理引擎和UI事件系统,可构建基础但完整的交互框架。

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



