2013-02-13 48 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>(); 

希望我能帮上忙。 干杯!

相关问题