如何在移动游戏对象与另一个游戏对象碰撞时立即停止它?

时间:2016-03-14 13:12:32

标签: c# unity3d transform collision-detection collision

我有一个响铃作为游戏对象,我用键盘键在y轴上上下移动。

作为信息:两个游戏对象都附有刚体以及对撞机。

这里有一些代码:

// get key up and the ring will move upwards
    if (Input.GetKey (KeyCode.UpArrow)&&(shouldMove))
    {
        transform.position += Vector3.up * speed * Time.deltaTime;
    }

    // get key down and the ring will move downwards
    if (Input.GetKey (KeyCode.DownArrow))
    {
        transform.position += Vector3.down * speed * Time.deltaTime;
    }

现在我想在它碰到另一个游戏对象时立即禁用此环的移动。我尝试了OnCollisionEnter函数,它给了我一个对象的信息(使用debug.log)但是我可以继续移动它并推送隐藏的游戏对象......

void OnCollisionEnter(Collision collision) {


    if (collision.gameObject.name == "Sphere") {            
        Debug.Log ("Hit Sphere");

    }

}

1 个答案:

答案 0 :(得分:1)

注意:您不能使用刚体的功能。如果您需要:Rigidbody.MovePosition(Vector3 position),您可以使用。

首先检查隐形GameObject的刚体IsKinematic字段true。或者删除它。之后你可以改变shouldMove = false所以它不会进入if语句。

bool shouldMove = true;
// get key up and the ring will move upwards
if (Input.GetKey (KeyCode.UpArrow)&&shouldMove)   ///Check shouldMove
{
    transform.position += Vector3.up * speed * Time.deltaTime;
}

// get key down and the ring will move downwards
if (Input.GetKey (KeyCode.DownArrow)&&shouldMove) ///Check shouldMove
{
    transform.position += Vector3.down * speed * Time.deltaTime;
}

void OnCollisionEnter(Collision collision) {
   if (collision.gameObject.name == "Sphere") {            
       Debug.Log ("Hit Sphere");
       shouldMove = false;   ///Change shouldMove
   }
}

如果你想要:不可见的物体不应该移动。您可以将碰撞者isTrigger字段检查为true。因此,您需要将OnCollisionEnter更改为OnTriggerEnter(Collider other),例如:

void OnTriggerEnter(Collider other) {
     if (other.gameObject.name == "Sphere") {            
           Debug.Log ("Hit Sphere");
           shouldMove = false; ///Change shouldMove
     }
}

如果你的戒指需要推动一些物体(不需要推动隐形物体,而是推动其他物体)。您可以创建新脚本并将此脚本添加到不可见对象。 (因此请检查Invisible objects Collider IsTrigger field true。) 在编辑器中拖放你的戒指到新的脚本RingController用于添加referance。

PS:以下代码YourRingControllScript需要更改实际的Ring Controller脚本名称。

public YourRingControllScript ringController;
void OnTriggerEnter(Collider other) {
     if (other.gameObject.name == "Sphere") {            
           Debug.Log ("Hit Sphere");
           ringController.shouldMove = false; ///Change shouldMove
     }
}

如果您的不可见对象在运行时实例化,那么您需要知道RingControllers持有者GameObject。您可以使用GameObject.Find("GameObjectName")找到GameObject。

您可以添加Start()方法:

void Start(){
    ringController = GameObject.Find("RingControllerGameObject").
                     GetComponent<YourRingControllScript>() as YourRingControllScript; //I think you don't need to add as YourRingControllScript if there is a problem without it you can add.
}