Monday, November 7, 2016

xna - How to make a platformer character go DOWN a 315 degree slope?


Alright, so I got this code I'm trying to write, but the player won't go down the slope, it goes down and up perfectly on the 45 degree slope, but the 315 degree one is a mess. it goes "up" the downward slope, get's stuck and some other stuff. Anyway here's the code:


//you're in a double for loop going through every tile in the map, the int's being used are x, and y

//check if the tile is a slope

if (lv.type[lv.tile[x, y]] == Tiles.SLOPE)
{
//create a rectangle collision box
Rectangle tileCol = new Rectangle(x * lv.tileSize, (y * lv.tileSize), lv.tileSize, lv.tileSize + 1);

//if player collision "col" collides with "tileCol" and you haven't done this before this itteration (only happens once per full double loop)
if (col.Intersects(tileCol) && !onSlope)
{
//get the angle of the tile
float angle = lv.angle[lv.tile[x, y]];


//get the x distance of how far away the player's right is inside the tile
float dist = (col.X + col.Width) - tileCol.X;


//constructs the opposite of a right triangle
float opposite = (float)(Math.Tan(MathHelper.ToRadians(angle)) * (dist));

if (angle < 90)
{

//if player's right is less then or equal to tile's right
if (col.X + col.Width <= tileCol.X + tileCol.Width)
{
//place player on slope. this works properly
pos.Y = tileCol.Y - opposite;
//tell the program we don't wanna go through this again until the next full loop starts.
onSlope = true;
}
}


else if (angle > 90){
if ((col.X + col.Width) >= tileCol.X)
{
//this is where the error is. the player goes "up" a slope that's 315 degrees, instead of down it.
//how do I make the player go down the slope that's 315 degrees!?
pos.Y = tileCol.Y + opposite;
onSlope = true;
}
}
}

}

currently using this code, it makes the player move in a 45 degree angle on the 315 degree blocks.


else if (angle > 90)
{

if (col.X >= tileCol.X)
{
pos.Y = tileCol.Y + lv.tileSize + (dist * -1);


onSlope = true;
}
}

Answer



Handle all slope tiles as a rise/run ratio. Each slope tile will have a ratio, and assuming 45 degrees means going up as you go right, 315 degrees will have a ratio of -1. Think back to basic coordinate algebra. Using the player's X position local to the tile, which is the run, solve for pos.Y by multiplying the X position by -1.


However since y = 0 is likely at the bottom of the tiles, you'll have to offset the height by adding the height of the tile.


So the player is colliding with a downwards sloping tile, the slope ratio is negative and the formula should be


pos.Y = lv.tileSize + (pos.X * slopeRatio)

Otherwise



pos.Y = pos.X * slopeRatio

if the slope is going up. Determine if the slope is upwards or downards by the sign of the slope ratio.


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