Menu
CoddyTech

Adding Vectors

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 24 of 85.

A Vector3 can be kept in a variable, and two of them add with +: x adds to x, y to y and z to z. That is how two pushes combine into one move. This beach ball rolls forward 2 units per second while the wind blows it 1 unit per second to the right:

Vector3 roll = new Vector3(0, 0, 2);
Vector3 wind = new Vector3(1, 0, 0);

void Update()
{
    Vector3 move = roll + wind;   // (1, 0, 2)
    transform.position += move * Time.deltaTime;
}

Multiplying a vector by a number multiplies each of its parts: wind * 3 is (3, 0, 0), a storm, and move * Time.deltaTime turns a move per second into the move for this frame. Subtraction also works part by part, and a - b is the step that leads from point b to point a. There is no * between two vectors: roll * wind does not compile.

challenge icon

Challenge

Easy

The river carries the boat, and the up arrow adds its motor.

  1. In Update(), start with Vector3 move = current;.
  2. While Input.GetKey(KeyCode.UpArrow) is true, add motor to move with +=.
  3. Add move * Time.deltaTime to transform.position.

Press Play: the boat drifts right, and crosses the river while you hold the up arrow. Then Check.

Try it yourself

using UnityEngine;

public class Boat : MonoBehaviour
{
    public Vector3 current = new Vector3(0, 0, 0);
    public Vector3 motor = new Vector3(0, 0, 0);

    void Update()
    {
        // The current always carries the boat.
        // While the up arrow is held, the motor pushes too.
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground