i’m following some tutorial as part of a unity course, and now i have created an object that chases the player object.
now i’m trying to get that object to stop when it arrives to a certain distance away from the player and based on an if statement that says that only if the object is 1.5f units away from the player, it starts moving towards it.
this is exactly the code the person used in that video, i get no errors (not in VS and not in unity) and the code simply doesn’t work. the object is not stopping until it ‘morphs’ with the player object.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Chaser : MonoBehaviour
{
public Transform targetTransform;
public float speed = 7f;
// Update is called once per frame
void Update()
{
Vector3 displacementFromTarget = targetTransform.position - transform.position;
Vector3 directionToTarget = displacementFromTarget.normalized;
Vector3 velocity = directionToTarget * speed;
transform.Translate(velocity * Time.deltaTime);
float distanceToTarget = displacementFromTarget.magnitude;
if (distanceToTarget > 3f)
{
transform.Translate(velocity * Time.deltaTime);
}
}
}
here’s the tutorial video; relevant part is at 10:32
thanks