- Home /
Make player move to location and stop within a certain distance
Hello everyone,
So I have a situation where the player presses an UI button and I need the player to move to the target and stop when within a certain distance, I tried numerous ways using while loops or for loop usually resulting in the editor freezing, which means the exit condition is never being met.
The piece that worked the best was the do and while loop:
if (option == 1)
{
float distance = Vector3.Distance(transform.position, combatManager.Target.transform.position);
distance = Mathf.RoundToInt(distance);
Debug.Log(distance.ToString());
do
{
Vector3 mdir = (transform.position - combatManager.Target.transform.position);
//playerAnim.SetTrigger("CombatStandard");
_charController.Move(-mdir * 3 * Time.deltaTime);
Debug.Log("moving");
distance = Vector3.Distance(transform.position, combatManager.Target.transform.position);
} while (distance > 5);
}
While this does work in moving the player closer, it does so instantly instead of over time.
any ideas?
here is a gif of whats happening:
Answer by GREYSETH · Jun 07, 2020 at 02:26 PM
@CryoGen14 Can you please be more specific on what you're trying to do? Because I might have a solution to your problem.
I want to have the player attack the currently assigned target when the player presses the attack button in the UI.
When the player presses the button, I want to have the player model(A) move from its current position towards the enemy(B), and then stop when it is within a certain distance of it.
I am trying to achieve this by checking the distance between A- and B and then moving A toward B until it reaches the distance specified, and the loop will end allowing the script to continue.
I have added a gif to the original post so you can see whats happening
I don't know how your script could look so complex but this is what I'm thinking :
float $$anonymous$$Distance = 5;
float distance;
void Update ()
{
// set distance variable to player and target position
if (option == 1)
{
if (distance >= $$anonymous$$Distance)
{
controller.$$anonymous$$ove(target.transform.position * speed * Time.deltaTime);
}else
{
// What you want to happen when the player is close
}
}
Your answer
Follow this Question
Related Questions
My Animation Loops 3/4 of the way through 3 Answers
Another function for activating a different script 0 Answers
How to check if the difference between any pair of numbers in an array is less than some value? 0 Answers
OVR Player Controller issuse with unity 5.5.0f3 2 Answers
Player keeps flying up 0 Answers