- Home /
Am I using MoveTowards and MovePosition wrong?
Vector2 inputDirection = input.normalized * 5f;
Vector2 moveDirection = rb.position + inputDirection;
Vector2 move = Vector2.MoveTowards(rb.position, moveDirection, 10f * Time.deltaTime);
rb.MovePosition(move);
My intention is to move a game object a specific amount of Unity units at a specific speed, in the direction of the 8-way input movement on a controller or keyboard.
With this code, I thought I was taking the movement input and adding 5 Unity units onto the direction and then moving the game object's rigidbody2D to that point with a speed of 10 (or whatever I want).
But, adding a distance onto the input direction doesn't do anything. Only changing the speed in MoveTowards changes the distance that the game object moves. What am I misunderstanding about how these two functions work, or interact with each other?
Answer by xxmariofer · Aug 24, 2021 at 07:19 AM
I would need a little bit of context, is that code in the update? but yes, you are missunderstanding how movetowards. let me explain:
the second parameter from MoveTowards is not a direction, is a position, what movetowards is doing is moving from 1 position (rb.position) in the direction towards the second position (moveDirection) by x amount (10 * Time.deltaTime).
what you should be doing if I understood you, is this:
Vector2 targetPosition;
void UpdateTheTargetPosition()
{
Vector2 inputDirection = input.normalized * 5f;
targetPosition = rb.position + inputDirection;
}
void FixedUpdate()
{
Vector2 move = Vector2.MoveTowards(rb.position, targetPosition, speed);//change speed for whatever float value, the higher the faster the "step" towards targetPosition
rb.MovePosition(move);
}
Note that he actually passes a position to MoveTowards, however he has named the variable "moveDirection" which of course is completely misleading.
However you are right about seperating the setting of the target position from the actual movement. If you set / update the target position every frame based on the current position, we would just continue to move into the input direction.
This appears to have fixed it. The entirety of this script was all being executed in FixedUpdate and I separated them into different functions as advised here and its working as intended now. Thanks for your help