David
David

Reputation: 770

Unity 2D How to respawn player at previous location after falling off ledge? 2D Top Down

I am working on a Top Down 2D game that has areas the character can fall off of. How can I "respawn" the player where they were before they walked off the ledge? I eventually want to add moving platforms as well. So if they fell off the moving platforms, they would go back to the last location they were on land.

Right now I have a tilemap collider 2D on the fall-able area that triggers the Coroutine.

So lets say the Character falls at position: (10, 10, 0.0) walking off the right side of the ledge. I would want them to respawn at (8, 10, 0.0) or something like that. Any ideas on how to accomplish this?

PlayerController.cs

private void OnTriggerEnter2D(Collider2D other)
{
    if (other.gameObject.layer == LayerMask.NameToLayer("Abyss"))
    {
        StartCoroutine(PlayerFall(gameObject, scaleRate, 0));
    }
}

IEnumerator PlayerFall(GameObject g, float scaleRate, float minScale)
{
    GameManager.instance.falling = true; // Disable movement while falling

    var currentPosition = transform.position; // Record player position
    Debug.Log("Character at position: " + currentPosition);

    float scale_y = g.transform.localScale.y;
    float scale_x = g.transform.localScale.x;
    while(scale_y > 0) // While the object is larger than desired
    {
        scale_y -= scaleRate * Time.deltaTime; // Calculate the new scale relative to the rate
        scale_x -= scaleRate * Time.deltaTime;
        Vector3 scale = g.transform.localScale;
        scale.y = scale_y;
        scale.x = scale_x;
        g.transform.localScale = scale;
        yield return null; // Wait a frame
    }

    var resetScale = _originalLocalScale; // Get original scale
    
    transform.localScale = resetScale; // Reset player scale after falling

    // Respawn player at last safe location

    GameManager.instance.falling = false; // Enable movement
    //End Coroutine
    yield break;
}

Scene with areas character can fall off

Upvotes: 0

Views: 1469

Answers (1)

Sven Viking
Sven Viking

Reputation: 2720

The easiest way would likely be to constantly save the player’s location while on solid (non-moving) ground — e.g. if( StandingOnGround() ) lastGroundPosition = transform.position; — and then return to that last known location on solid ground. That way you don’t need to worry about which side of a narrow chasm to respawn them on for example.

Upvotes: 0

Related Questions