How can I move an object to a new position smoothly in 2D?
So my player shoots a projectile and once it collides with a portal my player teleports to the new location, however i would prefer if my player moved smoothly to the new location instead of teleporting instantly. At the moment ive made it so on collision with my projectile the script in my portal object transforms the player position to the portals position. Then after some looking online i tried to use Vector2.MoveTowards. However it isn't working properly and he still moves instantly which i think is because it's only doing it whilst the collision is happening. I tried making it a function outside of the if statement but that didnt work. (I'm very new at coding and im learning as im going so any help would be appreciated thanks. :))
if (other.CompareTag("Projectile"))
{
Teleport();
}
void Teleport()
{
float step = speed * Time.deltaTime;
player.transform.position = Vector2.MoveTowards(player.transform.position, transform.position, step);
}
Answer by Dsiak · Nov 21, 2021 at 09:00 AM
Do you have this on a Coroutine or on an Update? It looks like its only been executing once. Try something like this see if it helps
private void OnCollisionEnter(Collision collision)
{
StartCoroutine(TeleportCoroutine());
}
IEnumerator TeleportCoroutine()
{
Vector2 current = player.transform.position;
Vector2 target = transform.position;
float step = speed * Time.deltaTime;
while (Vector2.Distance(current, target) > 0)
{
player.transform.position = Vector2.MoveTowards(player.transform.position, transform.position, step);
yield return new WaitForSeconds(0.1f);
}
}