2015-05-08 73 views
0

我編寫了一個腳本,只有當鼠標位於對象上時,才能在y軸上上下移動對象。我正在使用光線投射,我可以使用名稱並區分每個對象。但是,當我嘗試在光線投射時添加力時,所有附着腳本的對象都會移動。任何人都知道這是爲什麼?向一個對象添加強制力將附加腳本添加到所有具有腳本的對象

using UnityEngine; 
using System.Collections; 

public class BlockMove : MonoBehaviour 
{ 

    private bool dragOccuring = false; 
    private Vector3 lastMousePosition = Vector2.zero; 
    private float amountToMove = 0; 

    // Use this for initialization 
    void Start() 
    { 

    } 

    // Update is called once per frame 
    void Update() 
    { 
     Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition); 
     RaycastHit hit; 
     if (Input.GetMouseButtonDown (0) == true) { 
      dragOccuring = true; 
      if (Physics.Raycast (ray, out hit)) { 
       print (hit.collider.gameObject.name); 
       lastMousePosition = Input.mousePosition; 

      } 

     } else if (Input.GetMouseButton (0) == true) { 
      ray = Camera.main.ScreenPointToRay (Input.mousePosition); 

      if (Physics.Raycast (ray, out hit)) { 
       print (hit.collider.gameObject.name); 

       Vector3 mousePosition = Input.mousePosition; 
       Rigidbody rigidbody = GetComponent<Rigidbody>(); 

       if (lastMousePosition.y > mousePosition.y){ 
        rigidbody.AddForce (0, -Input.mousePosition.y, 0); 
       } else if (lastMousePosition.y == mousePosition.y){ 
        rigidbody.AddForce (0, 0, 0); 
       } 
       else{ 
        rigidbody.AddForce (0, Input.mousePosition.y, 0); 
       } 

       lastMousePosition = mousePosition; 
      } 
     } else if (Input.GetMouseButtonUp (0) == true) { 
      dragOccuring = true; 
      lastMousePosition = Vector3.zero; 
     } 
    } 
} 

回答

1

看起來你忘了比較光線投射命中的對象和腳本遊戲對象。如果沒有這個功能,當你單擊屏幕上的一個對象時,所有附有腳本的對象都會移動。

試着改變你的第二個如果塊類似

} else if (Input.GetMouseButton (0) == true) { 
    ray = Camera.main.ScreenPointToRay (Input.mousePosition); 

    if (Physics.Raycast (ray, out hit)) { 
     print (hit.collider.gameObject.name); 

     // If this is the clicked object 
     if(hit.collider.gameObject == gameObject){ 
      Vector3 mousePosition = Input.mousePosition; 
      Rigidbody rigidbody = GetComponent<Rigidbody>(); 

      if (lastMousePosition.y > mousePosition.y){ 
       rigidbody.AddForce (0, -Input.mousePosition.y, 0); 
      }else if (lastMousePosition.y == mousePosition.y){ 
       rigidbody.AddForce (0, 0, 0); 
      }else{ 
       rigidbody.AddForce (0, Input.mousePosition.y, 0); 
      } 
     } 
     lastMousePosition = mousePosition; 
    } 
} else if ... 

你甚至可以做的更好,並檢查這早些時候腳本,讓你的函數將結束不點擊的對象更快。