- Home /
Object moves toward another object when close
Hi all,
I currently have objects following my player with script that works, however I want the objects to only become active when the player draws near to them.
public class EnemyLook : MonoBehaviour {
public Transform target;
public GameObject player;
public float speed;
void Update() {
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, target.position, step);
transform.LookAt(target);
}
}
I wouldn't mind using raycast to do so, though I have no experience using rays and would greatly appreciate any help.
Thanks
Answer by Stormizin · Oct 29, 2013 at 07:04 PM
Check the object distance about the player and the object, with: Vector3.Distance
Then apply your script to calculate how many meters you want to active then.
Answer by Imankit · Oct 29, 2013 at 07:07 PM
Put a big Sphere Collider on your player and mark it as trigger
Then you just has to do this -
void OnTriggerStay(Collider col) {
if(col.collider.name == "Player"){
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, target.position, step);
transform.LookAt(target);
}
}
Your answer
Follow this Question
Related Questions
Transform.LookAt Seems To Cause Issues 1 Answer
Have An Object Rotate Around Transform A So That Transform B is Looking at Transform C (C#) 0 Answers
Set forward vector of an object to be EXACTLY equal to another vector. 2 Answers
Want to move object slowly to where the mouse clicks? 1 Answer
How to get a proper ramming effect? 1 Answer