2013-02-13 18 views
1

我在Unity3d製作紙牌遊戲。我以編程方式使用c#將卡片創建爲遊戲對象。我想知道如何讓每個對象(卡片)在點擊鼠標按鈕時移動,我嘗試使用Raycast對撞器,但它不起作用。我試圖訪問父類GameObject,它是整個網格的封面,它是碰撞對象/組件,通過它我想訪問一個孩子的GameObject(只是移動一個位置)。是否有一個簡單的方法來解決這個問題或你有沒有更好的方法以其他方式做到這一切?如何在腳本中訪問Collider的GameObject?

更新:

if (Input.GetMouseButton (0)) {      
    RaycastHit hit = new RaycastHit(); 
    Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition); 
    if (Physics.Raycast (ray, out hit)) { 
     print (hit.collider.gameObject.name); 
    } 
} 
+0

也許張貼光線投射撞機的代碼,您使用的? – 2013-02-13 11:54:39

+0

是的,我用下面的代碼,如果(Input.GetMouseButton(0)){ RaycastHit擊中=新RaycastHit(); 射線射線= Camera.main.ScreenPointToRay(Input.mousePosition); // **** 如果(Physics.Raycast(射線,出命中)){ 打印(hit.collider.gameObject.name); } } – Ananya 2013-02-13 12:37:57

回答

0

Input.GetMouseButton(0)應該Input.GetMouseButtonDown(0)

您嘗試使用Input.GetMouseButton(0),它註冊鼠標關閉的每一幀,與Input.GetMouseButtonDown(0)相反,它只在用戶單擊的第一幀上註冊。

示例代碼:

if (Input.GetMouseButtonDown(0)) 
    print ("Pressed"); 
else if (Input.GetMouseButtonUp(0)) 
    print ("Released"); 

if (Input.GetMouseButton(0)) 
    print ("Pressed"); 
else 
    print ("Not pressed"); 

如果不解決這個問題,嘗試用if (Physics.Raycast (ray, out hit, 1000)) {

0

我在這個問題跌跌撞撞藏漢更換if (Physics.Raycast (ray, out hit)) {,試試這個,而不是(順便說一句ü可以使用GetMouseButtonUp藏漢代替)

if (Input.GetMouseButtonDown (0)) 
{      
RaycastHit hit = new RaycastHit(); 
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition); 
if (Physics.Raycast (ray, out hit)) { 
    print (hit.collider.transform.gameObject.name); 
} 

}

對於某種方式,它可以通過轉換訪問,它爲我做了詭計! 如果你想訪問父:

hit.collider.transform.parent.gameObject; 

現在的孩子是有點棘手:

// You either access it by index number 
hit.collider.transform.getChild(int index); 
//Or you could access some of its component (I prefer this method) 
hit.collider.GetComponentInChildren<T>(); 

希望我能幫上忙。 乾杯!

相關問題