Diagonal Speed
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 27 of 85.
Hold the right and up arrows together and the raw axes give the direction (1, 0, 1). Its length, .magnitude, is the square root of 1 + 1, about 1.41. A walker moved by it covers 1.41 units on a diagonal in the time it covers 1 unit straight ahead: 41% faster.
.normalized gives a copy of a vector that points the same way and is exactly 1 unit long: (1, 0, 1) becomes about (0.71, 0, 0.71), and (0, 0, 5) becomes (0, 0, 1). Times a speed, it moves at that speed whatever the direction. This bee flies toward the flower at 2 units per second whether the flower is far or near; without .normalized it would fly faster the farther away the flower is:
public Vector3 flower = new Vector3(4, 1, 3);
public float speed = 2f;
void Update()
{
Vector3 toFlower = flower - transform.position;
transform.position += toFlower.normalized * speed * Time.deltaTime;
}Vector3.zero.normalized stays (0, 0, 0), since zero has no direction. v.normalized leaves v as it was; v.Normalize() changes v itself.
Challenge
EasyMake the walker move at the same speed on diagonals.
- In
Update(), buildVector3 direction = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));. - Add
direction.normalized * speed * Time.deltaTimetotransform.position.
Press Play and hold two arrows: the walker goes diagonally no faster than straight. Then Check.
Try it yourself
using UnityEngine;
public class Walker : MonoBehaviour
{
public float speed = 4f;
void Update()
{
// Arrows or WASD: move along x and z at speed, the same on diagonals.
}
}
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