My object will not stop moving.....please help??
Hey Guys,
So, I have the following code on an object that i wand to rotate towards a position and move forward if the variable distToForm is less than 5:
if (distToForm <= 5) {
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(GameObject.Find("Formation1").transform.position - transform.position), rotSpeed * Time.deltaTime);
transform.position += transform.forward * moveSpeed * Time.deltaTime;
}
Now, this does work perfectly but the object does not stop moving. It constantly keeps circling the point/location and will not stop moving even though the variable is less than 5.
I feel I am missing something obvious but I can not see it, is there anything wrong with this? Can anyone see anything that would cause this?
Answer by dan5071 · Feb 14, 2016 at 12:12 AM
I believe the problem is in your conditional statement. You have it set to perform actions only when the distance between your two objects is less than or equal to 5. This makes sense if you only want the rotating object to look at the other object if it is within a certain distance. However, you will also need a condition telling your script to stop these actions if the object is very close to its target. Otherwise, all sorts of funny things can happen to the transform's rotation once your object reaches its target position. One solution could be to change your if statement to:
if( distToForm <= 5 && distToForm >= 0.02 )
This modification will make your script stop all actions within that if statement once the object gets within 0.02 game units of its target (obviously, that can be changed to however close you want it to be). It just has to be at minimum small distance away from your moving object's target.
Your answer
Follow this Question
Related Questions
How can i move the box collider for a GameObject within a separate cube 0 Answers
Making a gameobject follow a player closely 1 Answer
Player Win and Display on-screen restart options and start menu 2D game 0 Answers
Have a GameObject to move only horizontally and not vertically 0 Answers
Moving gameObject without user input 2 Answers