Menu
CoddyTech

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 icon

Challenge

Easy

Slow the walker to half speed in the swamp.

  1. Below float s = speed;, write if (Vector3.Distance(transform.position, swamp) < 3f).
  2. Inside it, set s = speed / 2;. Leave the speed field 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

Practice on your own: Unity playground