【Unity3DRPG入门学习笔记第五卷】MouseManager 鼠标控制人物移动

创建一个空物体用来管理鼠标脚本

添加脚本 MouseManager.cs

示例代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

[System.Serializable]  // 指示可序列化的类或结构
public class EventVector3 : UnityEvent<Vector3> {
    
     }

public class MouseManager : MonoBehaviour
{
    
    
    // --- private -------------------------------------
    [Header("鼠标控制移动参数")]
    private RaycastHit m_HitInfo;

    // --- public --------------------------------------
    [Header("鼠标控制移动参数")]
    public EventVector3 m_OnMouseClicked;

    private void Update()
    {
    
    
        SetCursorTexture(); // 切换鼠标贴图
        MouseControl();     // 鼠标控制
    }

    /// <summary>
    /// @brief 切换鼠标贴图
    /// </summary>
    private void SetCursorTexture()
    {
    
    
        // 获取相机到鼠标点击点的射线
        // Camera.main
        // The first enabled Camera component that is tagged "MainCamera" (Read Only).
        // If there is no enabled Camera component with the "MainCamera" tag, this property is null.
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if (Physics.Raycast(ray, out m_HitInfo))
        {
    
    
            // 更换鼠标纹理
            // ...
        }
    }

    /// <summary>
    /// @brief 鼠标控制
    /// </summary>
    private void MouseControl()
    {
    
    
        // 如果在边界内点击了左键
        if (Input.GetMouseButtonDown(0) && m_HitInfo.collider != null)
        {
    
    
            if (m_HitInfo.collider.gameObject.CompareTag("Ground")) // 如果是地面
                m_OnMouseClicked?.Invoke(m_HitInfo.point);          // 如果对象不为空,则调用所有已注册的回调
        }
    }
}

✨参考文档 Camera.main
✨参考文档 Camera.ScreenPointToRay
✨参考文档 Physics.Raycast
✨参考文档 UnityEvent.Invoke



注意相机的标签是 MainCamera,文档有说明,然后代码中 EventVector3 类由于没有继承 MonoBehaviour,所以使用了 序列化类

The End.

猜你喜欢

转载自blog.csdn.net/weixin_50114337/article/details/128336903