Actively Controlling the Player Object

Before the player object can move under the control of the player, there needs to be a connection from the player’s mind, intent, and desire, to the game object.

For us, we’ll go through the player’s fingers, to a keyboard, through Unity’s input interface, to the game object.

And how are going to do this?

With CODE of course!

GOALS:

  • Move left and right with A and D keys
  • Move up and down with W and S keys

PROCESS:

  • open Project Settings in Unity
  • Edit -> Project Settings -> Input
  • Open Axes drop down
  • Only concerned with Horizontal and Vertical

GET THEIR NAMES and THEIR KEYS

REMEMBER:

  • on (x,y) axis, left and down are negative and up and right are positive

This will be our final code for horizontal movement:

Looks cool, but why??

  1. First we declare a float variable: horizontalInput
  2. Then we assign a value to it: Input.GetAxis(“Horizontal”);
  • we’re accessing the Input component and needing to access the axis, which in this case is the x, or Horizontal axis.

3. Then just like including the specific speed value, we include the variable in the multiplication between the Vector3 and the speed value.

Now let’s really wrinkle the brain…

horizontalInput is a variable that acts as a bool.

It’s reading and communicating whether or not there is an input happening.

It’s a 1 or a 0; it’s on or it’s off; it’s true there is input, or it’s false.

Remember: Vector3.right = Vector3(1, 0, 0) — moving in a positive direction.

But now it will only move if there is input; if it is true.

And this is using the positive direction key(s) — right arrow or D.

(Hint: IT’S ALL MATH)

The value of Vector3.right is 1.

The value of horizontalInput is 1.

The value of speed is 3.5f.

The value of Time.deltaTime is 1.

1 x 1 x 3.5 x 1 = 3.5 <- moving along the x-axis in the positive direction at a speed of 3.5 m/s

Here’s what it looks like when there is not input:

1 x 0 x 3.5 x 1 = 0 <- no movement along the x-axis.

Going left provides a true value for horizontalInput, but now it’s negative, using the left arrow key or A:

1 x -1 x 3.5 x 1 = -3.5 <- moving along the x-axis in the negative direction at a speed of 3.5 m/s

What about vertical movement?

It’s pretty much the same code except now we need a variable for vertical movement.

And presto, hey!

Now that we have active control, next up we’ll look at placing screen boundaries in the scene.

Thanks for reading!

I hope you find this helpful, and if you want to see what else I’ve got going on in my gamedev sojourn, sign up for my email list and don’t miss a bit of it!

https://thecliffbailey.com/emsu

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Cliff Bailey

Cliff Bailey

Software Developer w/ADHD learning and doing life.