繁体   English   中英

如何停止移动的物体

[英]How to stop a moving object

我的脚本是关于当我的球击中“陷阱对象”时,它将被移动到起始位置并在此处停止。 怎么做?

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

您是否在球上增加了某种形式的speedvelocity 如果这样做,则需要将其重置为零以阻止球滚动。

正如我在评论中提到的那样,您需要重置刚体的力以确保您的球完全停止。 以下代码可以解决您的问题。

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

该代码未经测试,因此如果不进行首次尝试编译就不会感到惊讶,因为我可能拼写了Rigidbody之类的东西。

(我也没有Unity上班,所以很难测试;-)

希望能帮助到你!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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