Menu
CoddyTech

Adding Vectors

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 17 of 67.

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

A river's current always carries the boat along. While the up arrow is held, the boat's motor pushes as well, on top of the current. Both are moves in units per second, set in the Inspector: the current is (1, 0, 0) and the motor (0, 0, 3).

Press Play and cross the river with the up arrow, then press 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.
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Scripting Basics