以下是一个简单的示例脚本,可以用于实现鼠标点击抽屉的打开和关闭:

using UnityEngine;

public class DrawerController : MonoBehaviour
{
    public GameObject drawer; // 抽屉对象
    public float openPosition = 1f; // 抽屉打开的位置
    public float closePosition = 0f; // 抽屉关闭的位置
    public float speed = 5f; // 抽屉移动的速度

    private bool isOpen = false; // 抽屉是否已经打开

    void Update()
    {
        // 如果鼠标左键被按下
        if (Input.GetMouseButtonDown(0))
        {
            // 获取鼠标点击的位置
            Vector3 mousePos = Input.mousePosition;
            mousePos.z = Camera.main.transform.position.z - drawer.transform.position.z;

            // 判断鼠标是否点击在抽屉上
            Collider2D hit = Physics2D.OverlapPoint(Camera.main.ScreenToWorldPoint(mousePos));
            if (hit && hit.gameObject == drawer)
            {
                // 如果抽屉已经打开,关闭抽屉
                if (isOpen)
                {
                    CloseDrawer();
                }
                // 如果抽屉已经关闭,打开抽屉
                else
                {
                    OpenDrawer();
                }
            }
        }
    }

    // 打开抽屉
    void OpenDrawer()
    {
        isOpen = true;
        StopAllCoroutines();
        StartCoroutine(MoveDrawer(openPosition));
    }

    // 关闭抽屉
    void CloseDrawer()
    {
        isOpen = false;
        StopAllCoroutines();
        StartCoroutine(MoveDrawer(closePosition));
    }

    // 移动抽屉到指定位置
    IEnumerator MoveDrawer(float targetPosition)
    {
        while (Mathf.Abs(drawer.transform.localPosition.x - targetPosition) > 0.01f)
        {
            drawer.transform.localPosition = Vector3.Lerp(drawer.transform.localPosition, new Vector3(targetPosition, 0f, 0f), Time.deltaTime * speed);
            yield return null;
        }
        drawer.transform.localPosition = new Vector3(targetPosition, 0f, 0f);
    }
}

在该脚本中,我们首先定义了一个公共变量 'drawer',用于存储抽屉的 GameObject 对象。然后定义了三个公共变量,分别用于存储抽屉打开的位置、抽屉关闭的位置和抽屉移动的速度。

在 'Update' 函数中,我们检测鼠标左键是否被按下,并获取鼠标点击的位置。然后使用 'Physics2D.OverlapPoint' 函数判断鼠标是否点击在抽屉上。如果是,则根据当前抽屉的状态,打开或关闭抽屉。

在打开和关闭抽屉的函数中,我们使用了协程 'MoveDrawer' 来移动抽屉到指定位置。在协程中,我们使用 'Vector3.Lerp' 函数来平滑移动抽屉,并使用 'StopAllCoroutines' 函数来停止之前的移动协程,以避免出现移动冲突的情况。

最后,将该脚本挂载到抽屉的 GameObject 上,并将抽屉的初始位置设置为关闭的位置即可。

Unity 鼠标点击控制抽屉打开关闭脚本

原文地址: https://www.cveoy.top/t/topic/jJWM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录