Unity move towards как работает

от admin

Vector3.MoveTowards

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Submission failed

For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Declaration

Parameters

current The position to move from.
target The position to move towards.
maxDistanceDelta Distance to move current per call.

Returns

Vector3 The new position.

Description

Calculate a position between the points specified by current and target , moving no farther than the distance specified by maxDistanceDelta .

Use the MoveTowards member to move an object at the current position toward the target position. By updating an object’s position each frame using the position calculated by this function, you can move it towards the target smoothly. Control the speed of movement with the maxDistanceDelta parameter. If the current position is already closer to the target than maxDistanceDelta, the value returned is equal to target ; the new position does not overshoot target . To make sure that object speed is independent of frame rate, multiply the maxDistanceDelta value by Time.deltaTime (or Time.fixedDeltaTime in a FixedUpdate loop).

Note that if you set maxDistanceDelta to a negative value, this function returns a position in the opposite direction from the target .

Vector3.MoveTowards

Вычислить положение между точками, указанными current и target , перемещаясь не дальше, чем на расстояние, указанное maxDistanceDelta .

Используйте элемент MoveTowards, чтобы переместить объект из current позиции в направлении target позиция. Обновляя положение объекта в каждом кадре, используя положение, вычисленное этой функцией, вы можете плавно перемещать его к цели. Управляйте скоростью движения с помощью параметра maxDistanceDelta . Если current положение уже ближе к target , чем maxDistanceDelta , возвращаемое значение равно target ; новая позиция не превышает target . Чтобы скорость объекта не зависела от частоты кадров, умножьте значение maxDistanceDelta на Time.deltaTime (или Time.fixedDeltaTime в цикле FixedUpdate).

Обратите внимание: если для параметра maxDistanceDelta задано отрицательное значение, эта функция возвращает позицию в противоположном направлении от target .

How to move a gameobject using movetowards

How do I make my GameObject move towards another GameObject using Vector3.MoveTowards method?

Heres my current code:

2 Answers 2

  • myGameObject — object you want to move
  • targetObject — object you are moving to
  • speed — float value to set the speed

First, let’s see the details and parameters of the method:

Understanding the parameters

  • Vector3 current: 3D vector of the object position (example: new Vector(0,0,1) )
  • Vector3 target: 3D vector of the target position (example: new Vector(3,4,5) )
  • maxDistanceDelta: maximum distance that the object will move when the method is called. (Example: if maxDistanceDelta is 1, the object will move 1 unit every time it’s called. In case we are not using Time.deltaTime it would move 50 units a second if the frame rate is 50)
Читать:
Как удалить teamviewer полностью с компьютера windows 10

Note: If the actual distance remaining is less than maxDistanceDelta , it will be placed on target position. Meaning the object will no longer move unless the target position changes.

How does Vector3.MoveTowards work in Unity?

What I mean is that I don’t understand what each part does, like in the example in the API, it didn’t give much on what did what! I kinda need this for an aim script in a shooter game I’m working on. Any help will be good, but a direct answer would be great!

Sourav Paul Roman's user avatar

1 Answer 1

You would use the function if you need to move an object towards a specific position that you know. The function takes in the current position of the object you want to move, the target position you want to reach, and the distance that you want to move towards the object.

So, if for an example you had an object at position (0, 0, 0), and you wanted to move it to the position (0, 7, 0), 2 units at the time, the function translates the position first from (0, 0, 0) to (0, 2, 0), then to (0, 4, 0), then to (0, 6, 0) and finally to (0, 7, 0). Notice, that in the last step, only one unit was moved. That way, you can safely call the function with values that don’t happen to match up at some point.

Now, Vector3.MoveTowards , can be used for a broad set of things, but for a basic example you could use it to move your player to where the user has clicked their mouse. The Unity docs link shows a very basic example, including a description, which should tell you enough about the usage (you could also try the script out, debug it and see what values get assigned and when).

You would simply feed in transform.position as the first parameter, the click position as the second position, and a suitable speed as the final parameter. I’m not an Unity user, so I can’t suggest a speed to use off-hand like this. Try out a few different values and see which feels good.

At the basic level, similar functionality can be achieved using a more basic linear interpolation, however this utility function guarantees that you will hit your target and the usage here is quite simple and easy.

Похожие статьи