Alright, so I need to know how to move a object up/down a 315 degree slope based on the code i have for moving said object up/down 45 degree slope. Currently the object moves up/down the 315 degree slope like it's 45 degrees, which is the wrong wa开发者_如何学Goy (going up and right when he should be going down and right).
Here is 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 >= tileCol.X)
{
//this is where the error is.
pos.Y = tileCol.Y + lv.tileSize + (dist * -1);
onSlope = true;
}
}
}
}
I don't fully understand your code because the way it's written, your player's position.Y in the "working" if loop is decremented from the top of the tile, effectively placing him near the top of the rectangle when he's supposed to be going up from the bottom of the slope. But - based on the code above, the following should work for all angles:
// Check if the tile is a slope
if (lv.type[lv.tile[x, y]] == Tiles.SLOPE)
{
// Create rectangle collision that is the same size as the tile
Rectangle tileCol = new Rectangle(x * lv.tileSize, y * lv.tileSize, lv.tileSize, lv.tileSize + 1);
// If player collision "col" standing on "tileCol"
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.Right - tileCol.X;
// Figure out how far to offset the player
float offset = (float)(Math.Tan(MathHelper.ToRadians(angle)) * (dist));
// If player's right is less then or equal to tile's right
if (col.Right <= tileCol.Right)
{
if (angle % 180 < 90)
{
pos.Y = tileCol.Bottom + offset;
onSlope = true;
}
else if (angle % 180 > 90)
{
pos.Y = tileCol.Top + offset;
onSlope = true;
}
}
}
45 degrees = 1/8 Pi. 315 degrees = 7/8 Pi. The tangent functions give you 1 and -1 respectively depending on the slope, and offset the character accordingly.
精彩评论