如何在Unity 3D中将对象移动到鼠标的z和y坐标

问题描述 投票:0回答:1

I'm trying to make the orange box follow my mouse. But with my current script, it only goes about a quarter of a unit towards the direction of my mouse, then stops. I am completely stuck & lost

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
1个回答
0
投票

尝试此脚本。我更改了世界位置计算和分配中的某些轴。问题是屏幕有两个轴,世界有三个轴。如果一个轴不是固定值,则需要获取该值,例如对地面进行光线投射。

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

        transform.position = new Vector3(worldPos.x, worldPos.y, worldPos.z);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.