Reputation: 243
I want to check when my ball stopped rolling (moving) for more then 5 seconds and then execute some code. I'm working on an android game and sometimes the ball gets stuck, the ball should be moving constantly so I want to check if it's moving and if it's not I need to respawn it.
What is the best way to do this?
Upvotes: 0
Views: 1129
Reputation: 4572
Put this as a C# script component onto your ball gameobject.
public class MyBall : MonoBehaviour{
private Transform _myTransform = null;
private Vector3 _lastPosition = null;
private void Awake(){
_myTransform = transform;
_lastPosition = _myTransform.position;
}
private void Update(){
if(_lastPosition == _myTransform.position){
Debug.Log("Did not move");
}else{
Debug.Log("Moved");
}
_lastPosition = _myTransform.position;
}
}
Upvotes: 0
Reputation: 190
You can create a simple counter for count 5 seconds and check the gameObject.getComponent.velocity.magnitude;
And create a if and check this magnitude is smaller than your wanted level
Upvotes: 0
Reputation: 15861
Each time Update
is called, you could check the magnitude of the object's velocity. If it's lower than a small amount (say 0.1 or something depending on your game's scale), add Time.deltaTime
to a member variable, otherwise, set that variable to 0. If that variable is ever over 5, you know your object has been not moving (or close) for 5 seconds. Then execute your code.
Upvotes: 3