- Home /
choosing between different targets
I have randomly spawning enemies in my scene and i would like them to randomly move towards a choice of 3 targets.
This is what i have so far
using UnityEngine;
using System.Collections;
public class discMovement : MonoBehaviour
{
public float speed = 8;
public Transform[] targets;
//The time (in seconds) in which the new prefab will be destroyed
public int destroyTime = 5;
public float timer = 0;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
float step = speed * Time.deltaTime;
foreach(Transform target in targets)
{
transform.position = Vector3.MoveTowards (transform.position, targets[Random.Range(0, targets.Length)].position, step);
}
if(gameObject.tag == "disc")
{
Destroy(gameObject, destroyTime);
}
}
}
I get no errors but my objects just kind of go crazy and start moving in loads of different directions, like its jumping between the targets very quickly. I'd appreciate if someone tell me where I'm going wrong?
Well, how often do you want them to switch targets? At the moment, you have them switching every frame.
I'd like them to randomly change between a 5-10 second timeframe lets say, so would I wrap a timer around the foreach maybe?
Answer by $$anonymous$$ · Jul 31, 2014 at 09:17 AM
The reaason why your object is moving like crazy is because you are setting its new target every frame in foreach loop, you can try something like this:
foreach (Transform target in targets)
{
// Choose new target every 5 seconds
if (System.Math.Round(Time.time, 2) % 5 == 0)
transform.position = Vector3.MoveTowards(transform.position, targets[Random.Range(0, targets.Length)].position, step);
}
The [x % 5] in if() statement represents how many seconds have to pass in order to change the target, you may tweak System.Math.Round() precision to more or less than 2 in parameter list to adapt its return value.
Your answer
Follow this Question
Related Questions
Random LookAt or Random Target 2 Answers
Moving rigidbodies at random 1 Answer
Stopping a rigidbody at target 1 Answer
Tower Target Random Tank 1 Answer
Move empty object random 1 Answer