Unity游戏开发:人物移动与相机跟随实战,UNIX下C语言编程与实践22-UNIX 文件其他属性获取:stat 结构与 localtime 函数的使用。

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系统依赖EventSystemUnityEngine.UI组件。以下是按钮点击事件的典型处理方式:

  1. 按钮绑定事件
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");
    }
}
  1. 事件触发扩展
    通过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事件系统,可构建基础但完整的交互框架。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值