简体   繁体   中英

How to stop a moving object

My script is about when my ball hit a "Trap Object", it'll be moved to start position and STOP right there. How to do that?

 void OnTriggerEnter (Collider other)
     {
         if (other.gameObject.CompareTag ( "Trap" ))
         {
             //move object to start position
             transform.position = startposition.transform.position;


             // I want to stop the object here, after it was moved to start position.   Because my ball was moving when it hit Trap object, so when it was moved to start position, it keeps rolling.
         }
 }

Do you add some form of speed or velocity to your ball? If you do, you need to reset this to zero to stop your ball from rolling.

As I mentioned in my comment, you need to reset the force of the rigidbody to make sure that your ball is stopped completely. The following code could fix your issue.

// LateUpdate is triggered after every other update is done, so this is
// perfect place to add update logic that needs to "override" anything
void LateUpdate() { 
  if(hasStopped) {
      hasStopped=false;
      var rigidbody = this.GetComponent<Rigidbody>();
      if(rigidbody) {
         rigidbody.isKinematic = true;
      }
  }
}

bool hasStopped;
void OnTriggerEnter (Collider other)
{
     if (other.gameObject.CompareTag ( "Trap" ))
     {
        var rigidbody = this.GetComponent<Rigidbody>();
        if(rigidbody) {
           // Setting isKinematic to False will ensure that this object
           // will not be affected by any force from the Update() function
           // In case the update function runs after this one xD
           rigidbody.isKinematic = false;

           // Reset the velocity
           rigidbody.velocity = Vector3.zero;
           rigidbody.angularVelocity = Vector3.zero;
           hasStopped = true;
        }
         //move object to start position
         transform.position = startposition.transform.position;


         // I want to stop the object here, after it was moved to start position.   Because my ball was moving when it hit Trap object, so when it was moved to start position, it keeps rolling.
     }
}

The code is untested, so I wouldnt be suprised if it didnt compile on first try, I could have misspelled Rigidbody or something.

(I don't have Unity at work either so hard to test ;-))

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM