Unity C# Character Control – Basic Player Movements

Methods for using transform.Translate for 2D and Using CharacterControl.Move for 2.5D 3D Environments
For 2D or 3D movement the below code examples to the player object through keyboard inputs. Learn how to use Unity’s API functions of transform.Translate and CharacterController to move your player. Using C# scripting to control your games character through coding behaviours can create unique movements with your game character.

2D Movement on the X and Y Axis – Using transform.Translate Method

The SerializedField is so you can edit the value in the inspector when you attach the script to the player’s object. Keeping the values private keeps your game from being altered from external sources, we don’t want people cheating in the game.

The _movementSpeed variable can be called anything but keep the description readable and relevant. The underscore is not necessary but it indicates for later that the variable is private. The value is a float so you may adjust to a specific speed such as 6.3f meters per second. Setting the movement speed for your player is important as you don’t want the player zooming off the screen when they hold the keys down.

TIP: The speed value can help in getting your game more fluid with your game style. For example, when making a speed run game where you have to rush through levels a higher value (Faster movement) would be a better option. Editing these values in the inspector when testing is quicker than changing values in your code. Being able to change while in-game to test your games values against obstacles or fluidity of motion.

Creating a variable for the input element can make your code easier to read. Creating the string variable directionH for the Horizontal input and directionV for the vertical movement. This reduces the vector3 value length and makes it easier to debug if something doesn’t work quite right.

The transform.Translate function tells the computer what to do with the object in this case we are moving our character. The vector3 function gives us 3 dimensions to work with, the direction, the speed and real-time. The first and second values are the input, direction* and _movementSpeed, that we have already discussed in that we made variables for those values. The only addition to giving the vector3 an initial direction for the input variable left, right, up, down, it only needs one value to understand what movement direction you want the object to perform. The final value is the real-time, here and now getting the current time value from the Unity API, this tracks movement speed and direction.

void update() {
// Broken down into basic parts allowing four directions
// Control the speed of your player movement.
[SerializeField] private float _movementSpeed = 4.0f;
// Horizontal Movement
string directionH = Input.GetAxis("Horizontal"); transform.Translate(vector3(directionH.right * speed * time.DeltaTime));
// Vertical Movement
string directionV = Input.GetAxis("Vertical"); transform.Translate(vector3(directionV.up * speed * time.DeltaTime)); }

3D Movement using CharacterControl.Move

We first need to add the component in the inspector called CharacterController. We will be calling from the unity API to control the character manually giving more control over the character’s movement in a 3D environment. First, we import the CharacterController from the unity engine API.

The rest of the variables here are for your movement speed, the max height you want to allow you player to jump, gravity how fast you want your character to fall and jump velocity. All are float values so you can adjust them in the inspector easily to fine-tune your games feel.

We will also create a private Class to keep the Update() section cleaner, as this is good practice for keeping your code clean and tidy. The vector3 values are different as we are using the API, the vector3 just needs the direction values at this point. Also creating a velocity value to use with our jump function.

Setting the space key using Input.GetKeyDown(KeyCode) function for our jump function. We use a conditional statement checking that the player is grounded and is allowed to jump. Calling the function CharacterController.isGrounded from Unity’s API checking that the player is allowed to jump and is touching the ground. Otherwise, the player could just keep jumping forever.

Then we allow the character to fall at a controlled rate using the countdown variable, _yVelocity -= _gravity. This variable will continue until the previous conditional statement isGrounded returns to a true value.

Now, all we need to do is add Time.deltaTime to keep the player movement controlled keeping our velocity within the game’s constraints. Using Unity’s API function CharacterController.Move.

The CharacterController Code
private CharacterController _controller;
[SerializeField] private float _movementSpeed = 4.0f;
[SerializeField] private float _jumpHeight = 5.0f;
[SerializeField] private float _gravity = 1.0f;
[SerializeField] private float _yVelocity;
void start() { _controller = GetComponent<CharacterController>();
}
void Update() {
PlayerMovement();
}
private void PlayerMovement() {
Vector3 direction = new Vector3(Input.GetAxis("Horizontal"), 0.0f, Input.GetAxis("Vertical"));
Vector3 velocity = direction * _movementSpeed;

if (_controller.isGrounded == true)
{
    if (Input.GetKeyDown(KeyCode.Space))
    { 
         _yVelocity = _jumpHeight; } } _yVelocity -= _gravity;
    }
    velocity.y = _yVelocity; _controller.Move(velocity * Time.deltaTime);
}

And that’s it for basic character movement control in Unity using C# scripting with the transform.Translate and CharacterController functions for Unity.

Sources:

The Ultimate Guide to Game Development with Unity 2019 https://docs.unity3d.com/ScriptReference/

Leave a Reply

Your email address will not be published. Required fields are marked *