Categories
Game Creation Mastering Development

Apply external effects to player movement

In a 2D downhill game with the following, custom movement code, how do I apply external effects to the player’s movement?

For example, when the player hits an obstacle, I want them to get bounced off the obstacle and briefly stop before they are able to continue moving. How do I best integrate those types of external effects into my movement code in a way that is scalable?

private void UpdatePlayerVelocity()
{
    // Calculate the player's vertical movement speed
    float speedY = maxSpeed.y * Time.fixedDeltaTime;

    // Calculate the player's horizontal movement speed
    float speedX = inputDirectionX * maxSpeed.x * Time.fixedDeltaTime;

    // Set the player's new velocity
    rb.velocity = new Vector2(speedX, speedY);
}

My player-obstacle collision is handled in the obstacle class, and I am using an action to notify the player about the collision. So I have the ability to have a corresponding method in the player class that get’s called when the collision occurs:

public void OnPlayerCollidedWithObstacle()
{
    // TODO:
    // Integrate the following into the above movement code ???
    // 1. Bounce the player off the obstacle
    // 2. Briefly stop the player from moving
    // 3. Continue moving
}

As a first step, I am thinking to wrap my default movement code in a bool check, so that it doesn’t get run when the collision movement code is run.

However, I was hoping for a better, more scalable way?

PS: I would like to keep my movement code custom, so no Unity physics / AddForce / etc.

Leave a Reply

Your email address will not be published. Required fields are marked *