So I am trying to implement a grid based movement for my game and below is the code I have started on. He moves along the y asix by 0.7 every time the the “W” key is pressed and is to stop when his position is 0.2, but he doesn’t stop and instead he keeps going. I have rearranged the code every way I know how. What exactly am I missing. (This is in the “Update” method by the way)
if (transform.position.y != 0.2f)
{
if(Input.GetKeyDown(KeyCode.W))
{
position = transform.position;
position.y += 0.7f;
transform.position = position;
}
}
First suggestion - compare your floats by small epsilon (e.g. Math.Abs(f1-f2) > 0.0001f) to avoid cases when float value is not precise enough (e.g. instead of 1f it might be 1.000001f).
Second suggestion - do not compare position for equality. Since you add 0.7f it may easily pass through 0.2f. Like -0.8f, -0.1f, 0.6f, etc.
Thus use >= operator to cover such case:
if (transform.position.y >= 0.2f)
You and another friend of mine suggested the same thing, but I still had trouble getting it to work exactly as I needed. I found a work around to use that works good for my simple 3x3 grid movement.
void Update ()
{
position = transform.position;
//This part of the code controls movement
//based on the 3x3 grid
if(Input.GetKeyDown(KeyCode.W) && panel_y != 3)
{
panel_y += 1;
}
if(Input.GetKeyDown(KeyCode.S) && panel_y != 1)
{
panel_y -= 1;
}
if(Input.GetKeyDown(KeyCode.A) && panel_x != 3)
{
panel_x += 1;
}
if(Input.GetKeyDown(KeyCode.D) && panel_x != 1)
{
panel_x -= 1;
}
//This part of the code denote the positioning based
//on which panel you are standing on based off the y asix
if(panel_y == 1)
{
position.y = -1.4f;
transform.position = position;
}
else if(panel_y == 2)
{
position.y = -0.5f;
transform.position = position;
}
else if(panel_y == 3)
{
position.y = 0.2f;
transform.position = position;
}
//This part of the code denote the positioning based
//on which panel you are standing on based off the x asix
if (panel_x == 1)
{
position.x = -0.6f;
transform.position = position;
}
else if (panel_x == 2)
{
position.x = -1.9f;
transform.position = position;
}
else if (panel_x == 3)
{
position.x = -3.2f;
transform.position = position;
}
}