Pushable Blocks Locked to a Grid in Unity

Ryan Sweigart
Nerd For Tech
Published in
2 min readAug 27, 2021

Objective: Create a block that the player can push that stays locked to a grid.

Fail!

When our player inputs a direction, the movement script “looks” ahead for a “pushable” object. If it finds one, it blocks the player’s movement, but called the block’s Push method, passing-in the direction it is pushing and its speed.

If the block is not currently being pushed, it will check the direction it is to be pushed in. If that direction is clear (i.e., the CheckDirection method returns true), it will set its new _destination to be in that direction. Then it will set its _speed to a multiple of the player’s speed, just to insure that player can’t move into the same the space the block is vacating (I’m using 1.5 as my multiplier). Finally, it sets _isBeingPushed to true so it can’t be pushed again until it reaches its _destination.

In the Update method, if the block is very close its _destination, it will set itself to that position and set _isBeingPushed to false so it can be pushed again.

If it is not at its _destination, it will move towards it.

The block’s CheckDirection method is even simpler than of the player’s. We use a ray to check for a blocking object like a wall or another crate in the direction the block is to be pushed in. If there is another block or wall, we return false and the push is not allowed. If the space is clear, the block will be pushed.

If we wanted to get a little crazier, we could check if the next space had was Pushable, and if it was and the space after that was clear, we could allow the player to push two or more blocks!

--

--