- Home /
Grid based movement and collisions
Hi,
I'm currently trying to implement a game that makes use of grid based movement and I used the answer here http://answers.unity3d.com/questions/611343/movement-2d-in-a-grid.html
The issue I have is that if my character collides with an object to the right, and I press to move right again, the character keeps jarring against the object they collided with basically due the && condition
if(Input.GetKey(KeyCode.RightArrow) && tr.position == pos){
pos += Vector3.right/100 *24;
this.transform.localScale = new Vector3(-1,1,1);
}
Does anyone know how I can stop this from happening? I thought about adding a collided flag and checking if that was false before I move, but I can't get that work either due to that fact that it tries to move before the collision is detected. Would appreciate any ideas on how to get around this.
thanks
That code you link calculates a target position and then moves towards it. the target position is incremented by 1 each time you press a key in the direction of the key you press, but it doesn't take into account the fact that you might not be able to move.
Say the objects position and the target position is (0,0), and you're stood next to a wall. If you press right the new target position is (1,0), but there's a collider in the way, so it keeps trying to move towards the target but can't get there. Hence the jittering.
To fix it you could cast a ray from the current target position in direction you're trying to move to see if it's walkable before you update the target position.