【问题标题】:How can I disable Object control on mouse click?如何在鼠标单击时禁用对象控制?
【发布时间】:2015-11-26 19:18:30
【问题描述】:

当用户移动鼠标指针然后单击时,它是 x 轴对象。对象在相同的鼠标指针位置落在地面上。但是当物体下落时,如果用户移动指针的位置,它也会影响物体下落的位置。我只希望对象落在用户单击的那个位置,并且在落在地上时不控制对象。 代码:

public class Ball : MonoBehaviour {

    Rigidbody2D body;
    float mousePosInBlocks;

    void Start () {
        body = GetComponent<Rigidbody2D> ();
        body.isKinematic = true;

    }

    void Update () {

        if (Input.GetMouseButtonDown (0)) {

            body.isKinematic = false;
        }

        Vector3 ballPos = new Vector3 (0f, this.transform.position.y, 0f);
        mousePosInBlocks = Camera.main.ScreenToWorldPoint(Input.mousePosition).x;


        //not go outside from border
        ballPos.x = Mathf.Clamp (mousePosInBlocks, -2.40f, 2.40f);

        body.position = ballPos;
    }
}

【问题讨论】:

  • 在您的脚本中添加一个简单的bool,例如在用户单击鼠标左键后设置为bool hasClickedtrue。如果hasClicked == true,请不要再更改body.position。或者,依赖RigidbodyisKinematic 属性,您在左键单击后已将其设置为true
  • @MaximilianGerhardt 你能在你的答案中用上面的脚本写这段代码吗

标签: c# unity3d


【解决方案1】:

跟进我的评论。出现鼠标点击后退出该功能即可。真的没有比这更多的了。

public class Ball : MonoBehaviour {

    Rigidbody2D body;
    float mousePosInBlocks;
    bool wasDropped = false;

    void Start () {
        body = GetComponent<Rigidbody2D> ();
        body.isKinematic = true;
    }

    void Update () {
        //Don't do anything after the ball is dropped.
        if(wasDropped)
            return;

        if (Input.GetMouseButtonDown (0)) {
            body.isKinematic = false;
            wasDropped = true;
        }

        Vector3 ballPos = new Vector3 (0f, this.transform.position.y, 0f);
        mousePosInBlocks = Camera.main.ScreenToWorldPoint(Input.mousePosition).x;
        //not go outside from border
        ballPos.x = Mathf.Clamp (mousePosInBlocks, -2.40f, 2.40f);

        body.position = ballPos;
    }
}

【讨论】:

  • if(wasDropped) 返回;这是在做什么
  • 如果球落下,则退出函数(在这种情况下为Update()),这是在鼠标左键上设置的。它阻止执行它下面的所有代码,这会改变球的位置。
猜你喜欢
  • 2023-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多