Unity Player Movement In 2D

As I was telling you about in this post, I am trying to make my own 2D game, which will be a little RPG and have a heavy plot, hopefully.

So first thing I am going to do is to make a player. Introducing – the square!

This took 5 minutes.

I have a script for general movement, so I could use it with NPCs and cutscenes as well as the player movement, and a script for the players’ input.

Right now this is looking very basic.

The Update function contains conditions to each key pressed that calls the according moving function in the player class, with the speed.

There is a lot of code repetition going on here, and in the Movement class too.

I literally copied and pasted, just changing the direction of the Vector3. This can be improved a lot.

Improving the code

I can make all these Move functions into one, accepting the Transform of the character, the speed and the direction. Simple.

As to the player inputs, the Update function will fill up quickly when I add more inputs from the player, so I will separate it into functions, first one will be CheckMovementDirection – To check which of the keys – WASD, if any, are pressed.

Now our movement looks like this
Although there aren’t any major changes here, the update function will now look cleaner and the random key codes are all under the movement direction category, making the code more readable.

If this kind of explanations are interesting you, leave a like so I would know to make more of those 🙂

Writing my train of thought like this and explaining what I am about to do helps me greatly with motivation. It also helps me to not get distracted by shiny things like, I need to make my code better (boring…) but ooohh the player can move, now let’s make it bump into stuff, or pick up things… (exciting!)

I would love to hear about what motivates you with your work, is it a todo list that is satisfying to check off? or maybe something else. I follow this girl on Instagram, she has the most fun todo lists, that are basically a coloring page! link to one of her videos here.

Leave a comment

Create a website or blog at WordPress.com

Up ↑

Design a site like this with WordPress.com
Get started