- Home /
How can I get the precise transform position in Update?
Hello. I have a problem with my Player constantly moving on the x axis, as I'd like it to move when the user presses A or D, and stop moving when it reaches a whole integer on the x axis.
An example would be moving to transform.position.x = 2 and stopping.
bool MoveLeft = false;
bool MoveRight = false;
bool InMotion = false;
void Update () {
if (Input.GetKey(KeyCode.A) && InMotion == false)
{
MoveLeft = true;
}
if (Input.GetKeyUp(KeyCode.A) && InMotion == false)
{
MoveLeft = false;
}
if (Input.GetKey(KeyCode.D) && InMotion == false)
{
MoveRight = true;
}
if (Input.GetKeyUp(KeyCode.D) && InMotion == false)
{
MoveRight = false;
}
if (MoveLeft == true || MoveRight == true)
{
if (MoveLeft == true)
{
InMotion = true;
transform.Translate(new Vector3(-1, 0, 1) * Time.deltaTime * 3);
if (transform.position.x % 1 == 0)
{
InMotion = false;
MoveLeft = false;
}
}
else if (MoveRight == true)
{
InMotion = true;
transform.Translate(new Vector3(1, 0, 1) * Time.deltaTime * 3);
if (transform.position.x % 1 == 0)
{
InMotion = false;
MoveRight = false;
}
}
}
else
{
transform.Translate(new Vector3(0, 0, 1) * Time.deltaTime * 5);
}
}
Changing if (transform.position.x % 1 == 0) statement to >= 0.98 works, but it is not as precise as I would like it to be. Is there a way around this, or am I missing something?
Answer by Matt1000 · Nov 15, 2018 at 02:17 PM
You just won't be able to because your object never actually IS on x = 2. The reason is that game Physics doesn't work like the real one. Objects don't go through all the intermediate points between two positions. They just teleport to it. Tus, you cant check if it IS in a position but rather if it is near.
In other words, you SHOULD and MUST use the >= 0.98. or even 0.99, depending on your speed. However, that doesn't mean that your object needs to stay there. once you know it's near an integer position you can just round it so it is in the exact spot. Example:
if (transform.position.x % 1 == 0)
{
transform.position = new Vector3(int.Round(transform.position.x), transform.position.y,
transform.position.z);
InMotion = false;
MoveRight = false;
}
Anyhow, you should be very careful of how you do this because once the player is in this position you may not be able to take him out of it since it will always enter in the if clause. Perhaps using coroutines moving the player is a better approach but that's a totally different script.