2D Player Setup (1): Movement and Jumping

Marcus Ansley
3 min readSep 7, 2021

--

I recently started work on this Player script for the 2D mobile adventure game project, and prioritised getting the movement and jumping logic down first. Rather than use Unity’s CharacterController component as we’ve done previously specifically the CharacterController.Move() method and CharacterController.isGrounded boolean), I’m working instead with just a BoxCollider2D and RigidBody2D components.

In particular, I’m taking the player’s horizontal input (multiplied by a speed variable) and changing the RigidBody’s velocity accordingly in order to give the player some movement. The RigidBody’s taking care of gravity, so those variables are on the component rather than in the script this time.

As for the Jumping code, I’ve got some logic in place to check whether the player’s grounded as well as whether we’re in a ‘cooldown’ period or not (just to get around a glitch in this):

The ‘CheckGrounded’ method returns a boolean, and I ended up testing out two solutions for determining whether the player is currently grounded: one which checks the RigidBody’s current velocity on the y axis, and the other which uses RaycastHit2D to cast a raycast down from the player to detect whether they’re on a surface:

The “1 << 8” part essentially just means I’m only looking for collisions with layermask 8 in my project (which I’ve set to be “Ground”). We could also just have a public LayerMask variable, but I really should try to get more comfortable with the bitwise/bit shift operators 😛

Initially I found checking for velocity worked well enough, but later found it caused a few too many bugs (at least for me). I’m opting for the second of these solutions at the moment, and will probably remove the initial once I’m certain I’ll have no use for it.

As you might have noticed, I’ve got some references to a PlayerAnimation custom script, which stores most of the code associated with animating and orienting the player’s sprite appropriately (which is being kept on a child GameObject). I’ll cover the animations side of this in a subsequent article, and I’ll include the full code I’m working with for the Player class below 😉

--

--

Marcus Ansley
Marcus Ansley

Written by Marcus Ansley

Game Developer | Game Design and Literature Graduate

No responses yet