2015-11-26 42 views
1

當用戶移動鼠標指針然後單擊時,它是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; 
    } 
} 
+0

在腳本中添加一個簡單的'bool',就像'bool hasClicked'一樣,在用戶單擊鼠標左鍵後將其設置爲'true'。如果'hasClicked == true',則不要再更改'body.position'。或者,依靠'Rigidbody'的'isKinematic'屬性,在左鍵單擊後,您將其設置爲'true'。 –

+0

@MaximilianGerhardt如果(被提取) 返回,您可以使用上述腳本在您的答案 –

回答

0

從我的評論Folloup。點擊鼠標後,退出該功能。真的沒有比這更多。

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; 
    } 
} 
+0

中編寫此代碼嗎?這是幹什麼的 –

+0

退出函數(在這種情況下爲'Update()'),如果球被丟棄,它被設置在鼠標左鍵上。它阻止了它下面的所有代碼的執行,這改變了球的位置。 –