# Unity 2d: How stop movement when object hit a wall

I created a square that slides on a flat ground.

public class PlayerMoveScript : MonoBehaviour
{

float move = 0;

void Start (){}

void FixedUpdate ()
{
if (move == 0) {
move = Input.GetAxis ("Horizontal");
if (move != 0) {
move = 15*Mathf.Sign(move);
rigidbody2D.velocity += new Vector2 (move, rigidbody2D.velocity.y);
}
} else
{
rigidbody2D.velocity = new Vector2 (move, rigidbody2D.velocity.y);
}

}
}


On both sides of the ground lies a wall, when the square hits a wall and stops his movement, the square instead continues to push in his direction. What I trying to do, is that when the square hits the wall, the square stop the movement and stop to push on the wall, in a way that the player can choose a new direction until the square will hit a new wall.

So imagine a big picture frame, a little square lies on the center.

1. The player hit the down key
2. The square starts to move down, with a constant velocity
3. The square hits the bottom side of the frame, and it stops
4. The player choose a new direction.
5. The square starts to move in the new direction
6. Back to 2

N.B: The walls are rigid bodies 2d with a box collider 2d.

• You should turn around 3 and 2 and introduce a new position property. 2: Calculate new position and see if this is a valid position. 3: Move the square to that position. I remember that unity has some kind of capsule for collision detection. Mar 26, 2014 at 7:05

I would keep track of the current direction and reset it every time the box collides with a wall, like so:

public float speed;

private Vector3 currentDirection = Vector3.zero;

void Update()
{
if (currentDirection.Equals(Vector3.zero))
{
Vector3 inputDirection = new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0);
if (!inputDirection.Equals(Vector3.zero))
{
currentDirection = inputDirection;
this.rigidbody2D.velocity = currentDirection * speed;
}
}
}

void OnCollisionEnter2D(Collision2D col)
{
currentDirection = Vector3.zero;
this.rigidbody2D.velocity = Vector3.zero;
}


Based on how you explained your movement one simple way of doing it is...

Raycast in the direction you move there are only four directions so everytime you move

1. Raycast in the direction you are moving.
2. In your update once the raycast gets within a certain distance say 0.2 unity units..
3. dont allow movement in that direction
4. and so once the player pushes a button in that direction you raycast to see if there a wall

For this setup to work you just will need 8 raycasts two for each direction you can move to define the width of the object.

The benefit of doing it this way is that you can keep a certain distance away from your box in otherwords you can define at what distance you want to stop before a collision actually happens which is what you probably want.

Also make sure to raycast only when you are moving.