Transform GameObject
I am trying to make an Object move to a Cube wich is stored in an Array.
The Array is filled with gameObjects with a tag.
I can get the Object to move instantly to the cube, but not slowly like its walking to it.
This is my script:
var moveTo : GameObject;
function Update(){
print(FindClosestEnemy().name);
}
function FindClosestEnemy():GameObj开发者_开发问答ect{
var chasePoints : GameObject[];
chasePoints = GameObject.FindGameObjectsWithTag("chasePoint");
var closest : GameObject;
var distance = Mathf.Infinity;
var position = transform.position;
for(var go: GameObject in chasePoints){
var diff = (go.transform.position-position);
var curDistance = diff.sqrMagnitude;
if(curDistance < distance){
closest = go;
moveTo = closest;
transform.position -= moveTo.transform.position;
distance = curDistance;
}
}
return closest;
}
I also tried the Time.deltaTime
thing, but then it teleports far away from the cube.
And just converting it to Transform Array isnt working out either :( Any ideas to make this work?
Help is much appreciated :) Thanks in advance!
It looks like you are doing the whole transformation in one frame. You need to pick a velocity and apply it to the object for each frame. You know the from and to. Pick how long you want it to take and update it incrementally. Remember that you cannot be sure there will be 60 frames a second so take that into account.
You can use Vector3.MoveTowards
For maxDistanceDelta you choose a velocity and multiply it with Time.deltaTime to be frame-length-independant:
Vector3.MoveTowards(transform.position, moveTo.transform.position, speed * Time.deltaTime);
精彩评论