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
EasyThe river carries the boat, and the up arrow adds its motor.
- In
Update(), start withVector3 move = current;. - While
Input.GetKey(KeyCode.UpArrow)is true, addmotortomovewith+=. - Add
move * Time.deltaTimetotransform.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
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground