# moving in a grid (2D)

i made a script that makes player moving in a grid (like in the old pokemon games)…

the problem i have is that if i run against a wall the player trys to go into the position in the wall and get stuck…

``````void Start()
{
pos = transform.position;
tr = transform;
}

void Update()
{

if (Input.GetKey(KeyCode.D) && tr.position == pos)
{
pos += Vector3.right;
}
else if (Input.GetKey(KeyCode.A) && tr.position == pos)
{
pos += Vector3.left;
}
else if (Input.GetKey(KeyCode.W) && tr.position == pos)
{
pos += Vector3.up;
}
else if (Input.GetKey(KeyCode.S) && tr.position == pos)
{
pos += Vector3.down;
}

transform.position = Vector3.MoveTowards(transform.position, pos, Time.deltaTime * speed);
}
``````

i tried to fix that bug, but all i tried failed and unity crashes everytime:

``````void Start()
{
public float speed = 2.0f;
Vector3 pos;
Transform tr;
public double time = 1000;
public int i = 0;
time = time * 1000000000;
pos = transform.position;
tr = transform;
time = time * Time.deltaTime;
}

void Update()
{
if (Input.GetKey(KeyCode.D) && tr.position == pos)
{
while (i < time)
{
i++;
pos += Vector3.right;
transform.position = Vector3.MoveTowards(transform.position, pos, Time.deltaTime * speed);
}
}
else if (Input.GetKey(KeyCode.A) && tr.position == pos)
{
while (i < time)
{
i++;
pos += Vector3.left;
transform.position = Vector3.MoveTowards(transform.position, pos, Time.deltaTime * speed);
}
}
else if (Input.GetKey(KeyCode.W) && tr.position == pos)
{
while (i < time)
{
i++;
pos += Vector3.up;
transform.position = Vector3.MoveTowards(transform.position, pos, Time.deltaTime * speed);
}
}
else if (Input.GetKey(KeyCode.S) && tr.position == pos)
{
while (i < time)
{
i++;
pos += Vector3.down;
transform.position = Vector3.MoveTowards(transform.position, pos, Time.deltaTime * speed);
}
}
i = 0;
}
``````

Note, I didn’t read your code too much, but I think I see what you are doing.

If you want to make movement work with MoveTowards or any other movement method so that you don’t end up inside other objects, you’ll have to first do a check in direction you try to move. Otherwise you are just blindly moving in directions that might have walls… which makes no sense.

See: Unity Connect

If your game is tile based, also then consider changing the whole collision checking to be driven by data, check your collision from array of tiles instead - this could be just 0s and 1s describing walkable and non walkable positions of level.

The while loop thing in second code listing doesn’t make any sense.