2015-10-13 85 views
0

我的腳本是關於我的球何時擊中「陷阱對象」,它將移動到開始位置並在那裏停止。怎麼做?如何停止移動物體

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

您將不得不重置當前的力並將其設置爲0。一種方法是將Rigidbody(ball)設置爲.isKinematic = false,並將velocity和angularVelocity設置爲vector3.zero。然後將isKinatic設置爲true。 –

回答

0

正如我在我的評論中提到的,您需要重置剛體的力量以確保您的球完全停止。以下代碼可以解決您的問題。

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

的代碼是未經測試,所以如果它沒有彙編的第一次嘗試我不會感到驚訝,我能有拼寫錯誤剛體什麼的。

(我沒有統一的工作要麼這麼難考;-))

希望它能幫助!

+0

它的工作。非常感謝。但是你的代碼錯過了一個聲明,將isKinematic設置爲false。無論如何謝謝你 –

+0

我很高興它爲你工作! :D但是,對於我錯過了「isKinematic = false」陳述,你是什麼意思?由於它顯然在我發佈的代碼中:-) –

0

你添加某種形式的speedvelocity到你的球?如果你這樣做,你需要將其重置爲零以阻止球滾動。