📅  最后修改于: 2023-12-03 15:20:52.150000             🧑  作者: Mango
Unity MoveTowards is a method that allows you to move an object gradually from its current position to a target position over a period of time. In this tutorial, we will learn to use the MoveTowards method for 2D games in Unity using C#.
To start, create a new 2D project in Unity and create a new C# Script. Name the script Move2D and attach it to a game object in the scene.
The MoveTowards method takes three parameters: the current position, the target position, and the maximum distance the object can move in one frame. Here is the syntax for MoveTowards:
public static float MoveTowards(float current, float target, float maxDistanceDelta)
The method returns a float value that represents the new position of the object.
Now let's see how we can use the MoveTowards method to move a sprite from one position to another in a 2D game.
First, we need to define the current position and target position of the object:
public class Move2D : MonoBehaviour {
public Vector2 startingPosition;
public Vector2 targetPosition;
public float speed;
void Start() {
startingPosition = transform.position;
targetPosition = new Vector2(5, 0);
speed = 2f;
}
void Update() {
transform.position = Vector2.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime);
}
}
In the Start method, we define the starting position as the current position of the object, the target position as a new Vector2(5,0), and the speed as 2.
In the Update method, we use the MoveTowards method to move the object from its current position to the target position with the specified speed. We use Time.deltaTime to ensure that the object moves at a consistent speed regardless of the frame rate.
And that's it! You can now run the game and see your object move from its starting position to the target position.
In this tutorial, we learned how to use the MoveTowards method to move an object gradually from its current position to a target position over a period of time in a 2D game using C# in Unity.