Reputation: 57
I have been searching and racking my brains for a while now to try and get this code working, to no avail. Hopefully you guys can help. I have a simple set up with a cube that moves position every frame. I need the cube to go to an x position when it reaches a different location.
Example: Cube starts at position 0, moves forward in the x axis until it gets to position 15, then reverts back to 0 and stops.
Vector3 startingPosition;
void Start ()
{
startingPosition = gameObject.transform.position;
}
void Update ()
{
if (gameObject.transform.position.x == 15) {
gameObject.transform.position = startingPosition;
} else {
float translation = Time.deltaTime * 2;
transform.Translate (0, 0, translation);
transform.Translate (Vector3.forward * translation);
}
}
}
Currently the cube continuously moves (no stopping point), it's x position having no affect on the positioning.
Upvotes: 1
Views: 10414
Reputation: 1
I have had an issue with a animation not working correctly and feel like I have scoured the internet for days trying to get it to work, so this was very helpful. In my situation, the animations' GameObject was at a position of y=1 and should have moved to y=9, but would not update unless I clicked the transition in the animator. I changed the code from x == 15
to y <= 9
and Vector3.forward
to Vector3.up
and it works perfectly now. Hope this might help someone else with the same issue. using Unity v 2017.1.2
Upvotes: 0
Reputation: 17248
Change your ==
to >=
and see if that makes a difference. My guess is that position.x
is never exactly equal to 15, either due to floating-point precision errors or due to your translation logic skipping over 15 from one frame to the next.
Upvotes: 1