I'm making a top down 2D game in unity in C#. Currently just getting movement set up, but I have already hit a problem that I can't figure out. The game is set up in a grid and I'm just using the arrow keys to move up, down, left and right. This is my script:
public class Player : MonoBehaviour
{
public float playerSpeed;
void FixedUpdate()
{
// Movement
if (transform.position.x < 0.25)
{
if (Input.GetKeyUp(KeyCode.RightArrow))
{
transform.position += new Vector3(playerSpeed, 0, 0);
}
}
if (transform.position.x > -0.3)
{
if (Input.GetKeyUp(KeyCode.LeftArrow))
{
transform.position += new Vector3(-playerSpeed, 0, 0);
}
}
if (transform.position.y < 0.15)
{
if (Input.GetKeyUp(KeyCode.UpArrow))
{
transform.position += new Vector3(0, playerSpeed, 0);
}
}
if (transform.position.y > -0.10)
{
if (Input.GetKeyUp(KeyCode.DownArrow))
{
transform.position += new Vector3(0, -playerSpeed, 0);
}
}
}
}
The first if statements for each direction is making sure the player doesn't leave the boundaries of the room. The annoying thing that is happening is when moving, it starts off in nice square numbers as intended like 0.05, 0.1, 0.15, etc, but then goes off course somehow and gives numbers like -0.05000001, -7.450581e-09, 0.04999999, which are close to the wanted numbers but not accurate enough. Any ideas? All suggestions appreciated.
Updatewould do. - Gunnar B.