首页 > 解决方案 > 如何在 Unity 3D 中将对象移动到鼠标的 z 和 y 坐标

问题描述

我试图让橙色框跟随我的鼠标。但是使用我当前的脚本,它只向我的鼠标方向移动大约四分之一单位,然后停止。我完全被困住了

using UnityEngine.EventSystems;
using UnityEngine;


public class drag : MonoBehaviour
{
    private void Update()
    {
        Vector2 mousePos = Input.mousePosition;
        Vector3 worldPos = Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, Camera.main.nearClipPlane));

        transform.position = new Vector3(transform.position.x, worldPos.y, worldPos.z);
    }
}

有什么帮助吗?这是为了游戏果酱,我还有大约 48 小时要完成。谢谢!

标签: c#unity3d

解决方案


干得好:

private void Update()
{
    // Get the mouse position
    Vector3 mousePos = Input.mousePosition;

    // Set the z component of the mouse position to the absolute distance between the camera's z and the object's z.
    mousePos.z = Mathf.Abs(Camera.main.transform.position.z - transform.position.z);

    // Determine the world position of the mouse pointer
    Vector3 worldPos = Camera.main.ScreenToWorldPoint(mousePos);

    // Update the position of the object
    transform.position = worldPos;
}

推荐阅读