- Home /
Question by
MorphiusX · May 11, 2014 at 04:46 PM ·
translatemove object
Make object move (not teleport) to another object
Im currently doing a small 2D game and am needing an enemy (in this case an ant) to move to an item (in this case a Cookie) I've been doing some research and can only find references where the ant teleports to the cookie and not moves to the cookie.
I've got the ants to find the closest cookie using the scripting references on unity just need to put it all together so the ant will move towards the cookie.
Thanks for your help
function Update(){
FindClosestEnemy();
print(FindClosestEnemy().name);
}
function FindClosestEnemy () : GameObject {
var gos : GameObject[];
gos = GameObject.FindGameObjectsWithTag("Cookie");
var closest : GameObject;
var distance = Mathf.Infinity;
var position = transform.position;
// Iterate through them and find the closest one
for (var go : GameObject in gos) {
var diff = (go.transform.position - position);
var curDistance = diff.sqrMagnitude;
if (curDistance < distance) {
closest = go;
distance = curDistance;
}
}
return closest;
}
Comment
Best Answer
Answer by Graham-Dunnett · May 11, 2014 at 04:50 PM
working script if anyone is interested
var speed: float;
private var closest : GameObject;
var target : Transform;
var targetFound : boolean;
function Update(){
FindClosestEnemy();
print(FindClosestEnemy().name);
if (targetFound == true){
$$anonymous$$ove();
}
}
function FindClosestEnemy () : GameObject {
var gos : GameObject[];
gos = GameObject.FindGameObjectsWithTag("Cookie");
var distance = $$anonymous$$athf.Infinity;
var position = transform.position;
// Iterate through them and find the closest one
for (var go : GameObject in gos) {
var diff = (go.transform.position - position);
var curDistance = diff.sqr$$anonymous$$agnitude;
if (curDistance < distance) {
closest = go;
distance = curDistance;
targetFound = true;
}
}
return closest;
}
function $$anonymous$$ove(){
target = closest.transform;
var step = speed * Time.deltaTime;
transform.position = Vector3.$$anonymous$$oveTowards(transform.position, target.position, step);
}
Your answer
Follow this Question
Related Questions
How to move character X and Z axis? 1 Answer
Move object upon hitting camera ray 1 Answer
Accelerometer start position 1 Answer
stop an elevator 1 Answer
translate C# with => to unityscript 2 Answers