Menu
CoddyTech

Distance Between Things

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

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 icon

Challenge

Easy

The walker crosses a swamp. Within 3 units of the swamp's center, swamp (set in the Inspector), it moves at half its speed; farther away, it moves at full speed. The movement code is written: work out the speed to use on each frame, and leave the speed field itself unchanged.

Press Play and walk through the swamp, then press 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;
    }
}
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