我的剧本是关于当我的球击中" Trap 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.
}
}
答案 0 :(得分:0)
你是否在球上添加了某种形式的speed
或velocity
?如果你这样做,你需要将其重置为零以阻止你的球滚动。
答案 1 :(得分: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.
}
}
代码是未经测试的,所以如果它在第一次尝试时没有编译我就不会感到惊讶,我可能会拼错Rigidbody或其他东西。
(我在工作中没有Unity这么难以测试; - ))
希望它有所帮助!