# Slopes in 2D Platformer

I'm dealing with Slopes in a 2D platformer game I'm developing in XNA Game Studio. I was really tired of trying without success, until I found this post: 45° Slopes in a Tile based 2D platformer, and I solved part of the problem with the bummzack answer.

Now I'm dealing with 2 more problems:

1) Inverted slopes:

The post says:

If you're only dealing with 45 degree angles, then it gets even simpler:

y1 = y + (x1 - x)

If the slope is the other way round, it's:

y1 = y + (v - (x1 - x))

My question is, what if I'm dealing with slopes with less than 45 degree angles? Does y1 = y + (v - (x1 - x)) work?

2) Going down the slope:

I can't find a better way to handle the "going down through the slope" situation, considering that my player can accelerate its velocity.

Edit: I was about to post a image but I guess I need to have more reputation he he he... What I'm trying to say with "going down" is like walking towards the opposite direction, assuming that if you are walking to the right, you are incrementing your Y position because you are climbing the slope, but if you are walking to the left, you are decrementing your Y position.

• Can you edit your question to better explain this "going down through the slope" situation? – MichaelHouse Jun 19 '12 at 22:51
• Yes, I just did :) – Carlosrdz1 Jun 19 '12 at 23:27
• So you have a problem detecting up slope vs down slope? – MichaelHouse Jun 20 '12 at 0:44

What you want to do is travel over that line and project the player's position onto the y-axis of the slope.

That sounds complicated, but it's alright.

Suppose we define a line as being between two points: p0 and p1. We can define the slope of the line as p1 - p0. What we need to do is take the x of the player's position and plug it into our line equation to get its y position.

In code:

if (
obj_player.x > obj_slope.GetStart().x &&
obj_player.x < obj_slope.GetEnd().x
)
{
// first we get the difference between the points
tb::Vec2 slope = obj_slope.GetEnd() - obj_slope.GetStart();

// to calculate the percentage of how far the player
// is on the slope, subtract the start position
// and divide by the horizontal slope
float percentage = (obj_player.x - obj_slope.GetStart().x) / slope.x;

// multiplying the percentage by the vertical slope gives us a value for y
obj_player.y = percentage * slope.y;
}


Obviously this won't solve all your problems. You'll still need to think about the following:

• What happens when the player "enters" the slope?
• What happens when she wants to jump while on a slope?
• What happens when she lands on a slope?