Distance Between Things
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 28 of 85.
Vector3.Distance(a, b) is how far apart two points are, in units, measured in a straight line through all three axes. It is the length of the step between them, (a - b).magnitude, so the order of a and b does not matter. From (0, 0, 0) to (3, 0, 4) it is 5.
Compare a distance with a number and a script knows when something is near. This camper can warm their hands only within 4 units of the campfire, whose position the Inspector sets:
public Vector3 campfire = new Vector3(3, 0, 4);
void Update()
{
float d = Vector3.Distance(transform.position, campfire);
if (d < 4f && Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("You warm your hands");
}
}The distance counts height too: a camper 5 units above the fire is 5 units away from it, not 0. When height should not count, compare two points at the same y.
Challenge
EasySlow the walker to half speed in the swamp.
- Below
float s = speed;, writeif (Vector3.Distance(transform.position, swamp) < 3f). - Inside it, set
s = speed / 2;. Leave thespeedfield and the movement lines as they are.
Press Play and walk right through the swamp: the walker slows down in it. Then Check.
Try it yourself
using UnityEngine;
public class Walker : MonoBehaviour
{
public float speed = 4f;
public Vector3 swamp = new Vector3(0, 0.5f, 0);
void Update()
{
float s = speed;
// Within 3 units of the swamp, move at half speed.
Vector3 direction = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
transform.position += direction.normalized * s * Time.deltaTime;
}
}
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