How to stop a moving game object as soon as it collides with another game object?

<>

This question already has an answer here:

Answers


Note: You don't use rigidbody's functionality. If you want: Rigidbody.MovePosition(Vector3 position) you can use.

First of all Check invisible GameObject's rigidbodiesIsKinematic field true. Or remove it. After than you can change shouldMove = false so It dont get in if statements.

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
   }
}

If you want that: Invisible object shouldn't move. You can check Colliders isTrigger field to true. So you need to change OnCollisionEnter to OnTriggerEnter(Collider other) like:

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

If your ring need push some objects(Dont need to push invisible objects, but push others). You can create new script and add this script to the invisible object. (So check Invisible objects Collider IsTrigger field true.) Than In editor drag&drop your ring to the new scripts RingController place for adding referance.

PS: Code below has YourRingControllScript need to change your actual Ring Controller script name.

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

If your invisible object instantiates at runtime so you need to know RingControllers holders GameObject. You can find GameObject with GameObject.Find("GameObjectName").

You can add Start() method this:

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.
}

Need Your Help

Loading a hash from a file and comparing

perl sorting hash

I have a file (abc.txt) which contains values such as :

How to find a table with Web::Scraper based on cell values?

perl

Want process a several html pages with tables.