Sunday, November 29, 2015

xna - 45° Slopes in a Tile based 2D platformer


I want to have simple 45° slopes in my tile based platformer, however I just cant seem to get the algorithm down. Please take a look at the code and video, maybe I'm missing the obvious?


//collisionRectangle is the collision rectangle of the player with 
//origin at the top left and width and height
//wantedPosition is the new position the player will be set to.
//this is determined elsewhere by checking the bottom center point of the players rect
if(_leftSlope || _rightSlope)
{
//Test bottom center point

var calculationPoint = new Vector2(collisionRectangle.Center.X, collisionRectangle.Bottom);
//Get the collision rectangle of the tile, origin is top-left
Rectangle cellRect =
_tileMap.CellWorldRectangle(
_tileMap.GetCellByPixel(calculationPoint));
//Calculate the new Y coordinate depending on if its a left or right slope
//CellSize = 8
float newY = _leftSlope
? (calculationPoint.X % CellSize) + cellRect.Y
: (-1 * (calculationPoint.X % CellSize) - CellSize) + cellRect.Y;

//reset variables so we dont jump in here next frame
_leftSlope = false;
_rightSlope = false;
//now change the players Y according to the difference of our calculation
wantedPosition.Y += newY - calculationPoint.Y;
}

Video of what it looks like: http://youtu.be/EKOWgD2muoc



Answer



From what I understand reading your question, you want to calculate the correct Y position, given a X position of the player. This is rather trivial. Have a look at this image:



slope


Assuming your slope-tile is at a given position x,y (origin is bottom left as in the image). You have the player position x1 and the width and the height of the sloped tile (u, v). x, y and x1 are world coordinates.


Given these parameters, your players Y-position (y1) would be:


y1 = y + (x1 - x) * (v / u)

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))

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...