Reputation: 273
I am very beginner in C# and Unity3D, so my question might be weird but please don't judge me. I have a trouble to figuring out what's wrong and why it doesn't work.
I have a ghost in the game, when I come closer to it, it has to move away from me. I have created collision around the ghost and added this script to it:
using UnityEngine;
using System.Collections;
public class MaidTriggeris : MonoBehaviour {
public GameObject light;
public GameObject sing;
public GameObject ghost;
public float speed;
public GameObject target;
// Use this for initialization
void Start () {
light.SetActive(true);
}
// Update is called once per frame
void OnTriggerEnter(){
light.SetActive (false);
DestroyObject (sing);
float step = speed * Time.deltaTime;
ghost.transform.position = Vector3.MoveTowards(ghost.transform.position, target.transform.position, step);
}
}
Anyway, when I move in the collision box, everything works (it destroys game object "sing" and sets light to "false"), however it never moves gameObject's "ghost" position to another object "target". My speed is set to 5 and all objects are assigned.
Upvotes: 0
Views: 2302
Reputation: 1398
Well, you are executing Vector3.MoveTowards
only once so your ghost
is moving only one step. What you need is to execute this in Update
with help of any flag on in Coroutine
under some condition.Like,
using UnityEngine;
using System.Collections;
public class MaidTriggeris : MonoBehaviour {
public GameObject light;
public GameObject sing;
public GameObject ghost;
public float speed;
public GameObject target;
// Use this for initialization
void Start () {
light.SetActive(true);
}
// Update is called once per frame
void OnTriggerEnter(){
light.SetActive (false);
DestroyObject (sing);
StartCoroutine("MoveGhost");
}
IEnumerator MoveGhost(){
while(Vector3.Distance(ghost.transform.position, target.transform.position) > 1.0f) // Change this value accordingly
{
float step = speed * Time.deltaTime;
ghost.transform.position = Vector3.MoveTowards(ghost.transform.position, target.transform.position, step);
yield return new WaitForEndOfFrame();
}
}
}
Above code snippet is not tested though. So make some tweaking if needed.
Upvotes: 2