C# 如何使用鼠标将选定的游戏对象移动到某个位置

C# 如何使用鼠标将选定的游戏对象移动到某个位置,c#,unity3d,C#,Unity3d,我需要帮助使用光线投射选择一个对象并将其移动到玩家左键单击的另一个位置。到目前为止,我做得很好,但是我无法得到选择移动的圆柱体。以下是我目前掌握的代码: public class ClicknDrag : MonoBehaviour { private GameObject selected; private bool unselected = true; void Update () { Ray ray = Camera.main.ScreenPointToRay(Input.mo

我需要帮助使用光线投射选择一个对象并将其移动到玩家左键单击的另一个位置。到目前为止,我做得很好,但是我无法得到选择移动的圆柱体。以下是我目前掌握的代码:

public class ClicknDrag : MonoBehaviour {

private GameObject selected;
private bool unselected = true;

void Update ()
{
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;

    if (Physics.Raycast(ray, out hit) && Input.GetMouseButtonDown(0) && hit.transform.tag == "Cylinder" && unselected == true)
    {
        selected = hit.transform.gameObject;
        unselected = false;
    }

    if (Physics.Raycast(ray, out hit) && unselected == false && Input.GetMouseButtonDown(0))
    {
        selected.transform.position = hit.transform.position;
        unselected = true;
    }
}

如果需要光线投射命中的位置,则需要使用hit.point,而不是hit.transform.position。hit.TRANSFORM.position将返回对象命中的位置

此外,在您的情况下,即使在选择之后,您仍然会使用光线投射撞击圆柱体,因此可以在选定对象时禁用该对象的碰撞器。这样,光线投射将忽略它,它将击中它找到的下一个对象(例如地板)


你应该这样做
物理。光线投射
只做一次。。。相当贵!此外,对
输入.GetMouseButtonDown
的检查也是多余的。并存储
Camera.main
的结果,这也是非常昂贵的(afaik在引擎盖下使用类似于
GameObjevt.FindWithTag(“MainCamera”)

另请注意:
GetMouseButtonDown(0)
仅在第一次按下按钮时在帧中返回一次true。稍后移动时,您可能更希望使用
GetMouseButton(0)
,该按钮为
true
,只要按钮保持按下状态

最后,如果您希望平滑移动到准确的命中位置,而不是命中对象位置,您可能希望使用
hit.point
而不是
hit.transform.position

unselected
标志有点多余:您可以直接使用
if(selected)
,然后将其重置为
selected=null

大概是

[SerializeField] private Camera _camera;

private void Awake ()
{
    if(!_camera) _camera = Camera.main;
}

private void Update()
{
    Ray ray = _camera.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;

    if (Physics.Raycast(ray, out hit) && hit.gameObject.CompareTag("Cylinder"))
    {
        // First click -> select object
        if(Input.GetMouseButtonDown(0) && !selected)
        {
            selected = hit.transform.gameObject;
        }
        // button stays pressed > move object
        else if (selected && Input.GetMouseButton(0))
        {
            selected.transform.position = hit.point;
        }
        // Second click release object
        else if(selected && Input.GetMouseButtonDown(0))
        {
            selected = null;
        }
    }
    // ToDo: What if the Raycast doesn't hit? Then you can't release object?
}