Prototype: Player Speed

Introduction

We’ll be building on the code we introduced in the last post. There, we created the Player GameObject and added simple controls via the Input Manager. Let’s now add the ability to adjust the speed of our player movement!

The Challenge

Today we want to extend the movement system by providing variable speed anybody on our team can easily tweak without the need for code modification. Providing levers for designers is incredibly efficient for both the prototype stage and beyond.

Introducing Speed

Let’s start simply by declaring a new private float variable named _speed and initialize it with a value of 5.0f.

Add Speed Variable

We’ll then translate the product of our direction and speed. Here, I’m multiplying the variables in a specific order, with the direction Vector3 at the end, to ensure we only multiply against it once, since otherwise we would have to multiply 3 times (x, y, z) per subsequent product.

Speed and Direction Product

Edit Speed via Inspector

We’ve made the speed variable private so that no other scripts can edit the speed field directly. So then, how do we then surface this as an editable field for ourselves and designers? By using the SerializeField attribute.

This attribute forces Unity to serialize private fields. Public fields automatically get this treatment, but SerializeField is the approach to take to get the same benefits for fields you want to be private.

Now switch to Unity, and once it compiles, you’ll see the speed input in the inspector.

Add SerializeField Attribute

Much better!

Player Speed Demo

Summary

Now we’ve added a speed variable to our player movement! Not only that, we’ve done it in such a way that anyone on our team could tweak the value and provide input with no coding required.

Stay tuned for the next entry. Take care.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s