The question is answered, right answer was accepted
Make Player Run and Walk at Different Distance
Hello, I'm controlling my player by using "click to move to target position" method. However, I want him to "walk to target" if I click at a distance that is closer to him and "run to target" if I click at a further distance. I already tried this, however, when my player runs to target, he switches to walk when he reaches the distance between him and the target position. I am new to Unity and I would be really appreciate if someone could come up with a solution. Thank you!
targetPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
` float dist = Vector3.Distance(targetPosition, transform.position);
if (dist.x >= 8)
{
Run();
}
else
{
Walk();
}
void Walk()
{
speed = 2.5f;
transform.position = Vector3.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime);
anim.SetBool("Run", false);
anim.SetBool("Walk", true);
if (transform.position == targetPosition)
{
isMoving = false;
anim.SetBool("Walk", false);
}
}
void Run()
{
speed = 3.5f;
transform.position = Vector3.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime);
anim.SetBool("Walk", false);
anim.SetBool("Run", true);
if (transform.position == targetPosition)
{
isMoving = false;
anim.SetBool("Run", false);
}
}
Answer by streeetwalker · Jun 29, 2020 at 05:40 AM
@kobatonguye, So, you don't want the character to switch back to walking after starting to run to the target location? Then only do the check when you first initiate the run or walk, do not constantly check the distance as it is moving.
We can't tell because you haven't provided the code that shows where your distance check is, but if that is in an Update loop it will check every frame, which is not where it should be given your problem.
Yes, it's in an Update loop, I'm trying to figure how to fix that or move it somewhere else.
How are you initiating the movement - using a key or a mouse button? Then put the code there where you first start the run or walk. Just make sure it does not run the check each frame.
Follow this Question
Related Questions
Shoot bullet towards mouse 0 Answers
Object dissapears on MoveTowards 1 Answer
MoveTowards works weird 0 Answers
Prefab clone to target 1 Answer