版本: Unity 6 (6000.0)
语言英语
  • C#

Vector3.MoveTowards

建议更改

成功!

感谢您帮助我们提高 Unity 文档的质量。虽然我们无法接受所有提交的内容,但我们会阅读用户提出的每项更改建议,并在适用的情况下进行更新。

关闭

提交失败

由于某种原因,您的更改建议无法提交。请<a>稍后再试</a>。感谢您抽出时间帮助我们提高 Unity 文档的质量。

关闭

取消

声明

public static Vector3 MoveTowards(Vector3 current, Vector3 target, float maxDistanceDelta);

参数

current 要移动的起始位置。
target 要移动到的目标位置。
maxDistanceDelta 每次调用移动 current 的距离。

返回值

Vector3 新位置。

描述

计算 currenttarget 指定的点之间的一个位置,移动距离不超过 maxDistanceDelta 指定的距离。

使用 MoveTowards 成员将对象从 current 位置移动到 target 位置。通过使用此函数计算的位置在每一帧更新对象的位置,您可以使对象平滑地移动到目标位置。使用 maxDistanceDelta 参数控制移动速度。如果 current 位置已经比 maxDistanceDelta 更靠近 target,则返回的值等于 target;新位置不会超过 target。要确保对象速度与帧速率无关,请将 maxDistanceDelta 值乘以 Time.deltaTime(或在 FixedUpdate 循环中乘以 Time.fixedDeltaTime)。

请注意,如果将 maxDistanceDelta 设置为负值,则此函数返回一个与 target 方向相反的位置。

using UnityEngine;

// Vector3.MoveTowards example.

// A cube can be moved around the world. It is kept inside a 1 unit by 1 unit // xz space. A small, long cylinder is created and positioned away from the center of // the 1x1 unit. The cylinder is moved between two locations. Each time the cylinder is // positioned the cube moves towards it. When the cube reaches the cylinder the cylinder // is re-positioned to the other location. The cube then changes direction and moves // towards the cylinder again. // // A floor object is created for you. // // To view this example, create a new 3d Project and create a Cube placed at // the origin. Create Example.cs and change the script code to that shown below. // Save the script and add to the Cube. // // Now run the example.

public class Example : MonoBehaviour { // Adjust the speed for the application. public float speed = 1.0f;

// The target (cylinder) position. private Transform target;

void Awake() { // Position the cube at the origin. transform.position = new Vector3(0.0f, 0.0f, 0.0f);

// Create and position the cylinder. Reduce the size. var cylinder = GameObject.CreatePrimitive(PrimitiveType.Cylinder); cylinder.transform.localScale = new Vector3(0.15f, 1.0f, 0.15f);

// Grab cylinder values and place on the target. target = cylinder.transform; target.transform.position = new Vector3(0.8f, 0.0f, 0.8f);

// Position the camera. Camera.main.transform.position = new Vector3(0.85f, 1.0f, -3.0f); Camera.main.transform.localEulerAngles = new Vector3(15.0f, -20.0f, -0.5f);

// Create and position the floor. GameObject floor = GameObject.CreatePrimitive(PrimitiveType.Plane); floor.transform.position = new Vector3(0.0f, -1.0f, 0.0f); }

void Update() { // Move our position a step closer to the target. var step = speed * Time.deltaTime; // calculate distance to move transform.position = Vector3.MoveTowards(transform.position, target.position, step);

// Check if the position of the cube and sphere are approximately equal. if (Vector3.Distance(transform.position, target.position) < 0.001f) { // Swap the position of the cylinder. target.position *= -1.0f; } } }