DEV Community

loading...
Cover image for Prototype: Player Movement

Prototype: Player Movement

justinhhorner profile image Justin Horner Originally published at justinhhorner.com ・3 min read

Introduction

Welcome to the first post in the series! I'm stoked to get started.

As I mentioned in the series introduction, we will begin by building a prototype to establish the basic mechanics and feel. Once we've done just enough to be confident in the idea, we'll then switch over to production-ready assets and clean up the code to ensure it is clean and maintainable.

I will create it in a new 3D project to quickly build the prototype using 3D primitives. Later we'll migrate to 2D. I will begin by setting the camera background to black and toggle the Scene window to 2D. I'm going to target a 16:9 aspect ratio, so I'll also set that for the Game window.

You may have it set to "Free Aspect" by default, if so click that and select 16:9 or create a custom aspect ratio if it's not furnished with the version of Unity you're using.

Camera Black Background

The Challenge

Our challenge is to create a Player GameObject and add horizontal and vertical movement via keyboard.

Create The Player

First, I'll create a Cube and name the GameObject Player. Then I'll move the player down a bit closer to the bottom in the Game window.

Player Placed on Bottom of Screen

Next, I'll create a new Player script and attach it to our Player GameObject.

Player GameObject with Script

Now, let's talk about the Input Manager.

The Input Manager

To control the player's movement, we'll take advantage of the Input Manager provided by Unity.

We're interested in the Horizontal and Vertical axes. These have several properties, such as negative and positive buttons (left and right), alt versions (a and d). When we request the current value of these axes, we'll get a float value between 0 and 1.

Input Manager Axes Expanded

To get the current value of these axes, I'll use the GetAxis static method on the Input class.

Finally, I'll use the transform's Translate method to move the transform in the direction and distance of the provided translation vector. We'll multiply the direction by Time.deltaTime to make ensure our movement is framerate independent. If you'r'e unfamiliar, you can read more about Time.deltaTime.

Full Player Movement Code

Here's the final result!

Moving the Player Around

Admittedly, this might be a bit anticlimactic, given the slow rate at which our player is moving. We'll address that in the next post so we can have a variable rate of speed.

Summary

That's it! We now a Player GameObject on-screen and controlling movement via script using the Input Manager's Horizontal and Vertical axes!

Stay tuned for the next post.
Take care.

Discussion (0)

Forem Open with the Forem app