UNITY 移动到指定位置的写法

时间:2023-12-30 22:53:05
//move towards a target at a set speed.
private void MoveTowardsTarget() {
//the speed, in units per second, we want to move towards the target
float speed = ;
//move towards the center of the world (or where ever you like)
Vector3 targetPosition = new Vector3(,,); Vector3 currentPosition = this.transform.position;
//first, check to see if we're close enough to the target
if(Vector3.Distance(currentPosition, targetPosition) > .1f) {
Vector3 directionOfTravel = targetPosition - currentPosition;
//now normalize the direction, since we only want the direction information
directionOfTravel.Normalize();
//scale the movement on each axis by the directionOfTravel vector components this.transform.Translate(
(directionOfTravel.x * speed * Time.deltaTime),
(directionOfTravel.y * speed * Time.deltaTime),
(directionOfTravel.z * speed * Time.deltaTime),
Space.World);
}
}