- Home /
moving an object when the character is not looking
i have an object and i want to put a heap of empty gameobjects with tags in my scene and the position of the object will be the closest one of those empty gameobjects, also i dont want it to be able to move when it is on the screen. how would i do this? also does anyone know how to put a bump map on a terrain texture?
Answer by Toby-Grierson · Aug 24, 2012 at 01:37 PM
One question at a time! I'll tackle the moving object.
I'm reading your question like so; you have object A, camera C and set of empties S.
When object A is not visible to camera C, you want to to move to the empty in set S which is closest to either the camera C (or character B).
Yessir? I'll answer.
So you need a component which you can add to object A which will move it. Let's call this MoveWhileHidden.
class MoveWhileHidden: MonoBehaviour
{
public Transform[] positions; //Use the inspect to add all the empties.
public Transform theChased; //We want to be close to this thing.
bool mayMove = false;
void OnBecameInvisible() {
mayMove = true;
}
void OnBecameVisible() {
mayMove = false;
}
//This may return null.
Transform findNearest()
{
Transform nearest = null;
float nearestDistance = float.MaxValue;
foreach(Transform t in positions)
{
float f = (t.position - theChased.position).sqrMagnitude;
if(f < nearestDistance)
{
nearestDistance = f;
nearest = t;
}
return t;
}
void Update()
{
if(mayMove)
{
Transform t = findNearest();
if(t != null)
{
transform.position = t.position;
}
}
}
Make sure to put the empties in there. You might also use a GameObject.Find[...] method with a tag to populate the list at runtime.
Please ask about the bump mapping in another thread.
$$anonymous$$ay I recommend starting and stopping a coroutine ins$$anonymous$$d of using may$$anonymous$$ove and Update. Then you could use a time interval ins$$anonymous$$d of updating every frame, which might be a bit too often.
There's a good idea. One must only take care to stop it correctly though because if the decision point is too far decoupled from the game's operation, it may accidentally move when it's in view. The cost is only O(n) with the number of potential points, so whether or not any effort to optimize is warranted does depend on platform target and if there's a few points or a few hundred.
Sure, it's not that important really (it must be my age, back then when I was young... ;) ), but there is no problem if you start / stop the coroutine where you set may$$anonymous$$ove now. You don't have to do any extra checks, because the coroutine is not running when the enemy is visible.