MoveTowards instantly repositioning object to target position
So I've been struggling with this for some time now...I read through all existing relevant answers but still couldn't manage to sort the issue out so here I am, humbling asking for any help y'all can provide. I want to use MoveTowards() to make my character slowly float towards the center of the screen when its Die() method is called (this happens when the attached HealthBar object reduces health to a value <= 0). The method call is working fine, but I'm stuck with two partially functional scenarios:
1) The character 'teleports' to the target position of Vector2.zero when the method is called
public void Die()
{
myRigidbody.gravityScale = 0f;
myRigidbody.velocity = Vector2.zero;
while (transform.position != Vector3.zero)
{
transform.position =
Vector2.MoveTowards(transform.position, Vector2.zero, 1f * Time.deltaTime);
}
}
2) The character moves a smidgeon of the way to the target position everytime the Die() is called
public void Die()
{
myRigidbody.gravityScale = 0f;
myRigidbody.velocity = Vector2.zero;
transform.position =
Vector2.MoveTowards(transform.position, Vector2.zero, 1f * Time.deltaTime);
}
Any ideas how I can fix this? All help greatly appreciated!!!
Answer by Lantian2018 · Jun 16, 2020 at 11:56 AM
Hello,
Where do you call your Die method? If you use MoveTowards outside the Update method of your MonoBehaviour class, your object will move 1f*Time.deltaTime at most.
You have to call moveTowards inside your Update method as long as your object isn't where you want it to be.
Answer by mbro514 · Jul 04, 2020 at 07:43 PM
With your first version of the script, the problem is that you're using a "while" loop, which only takes one frame to complete, instead of being completed over the course of a series of frames. This is what makes your character instantly go to (0, 0, 0). A Coroutine would probably solve your problem.
Your answer
Follow this Question
Related Questions
Having some problem with AI finding a vector3... 0 Answers
Object to walk forward, turn 180 and walk back 1 Answer
Vector3.MoveTowards moving transform 0 Answers
(26,47): error CS1525: Unexpected symbol `)' 1 Answer
List.FindIndex 1 Answer