I've been looking into adding 'sloping' tiles into my platform game and my first attempt at collision detection with these tiles has produced some promising results (considering it's a first attempt), however, there is something that I just can't work out.
First, some background.
My tiles (on my dev device which is a Google Nexus 10 tablet) are 102 pixels wide by 100 pixels tall (this was done on purpose so they fit better to the screen).
So, my 'slope tile' looks something like this:
Not being a perfect square, the slope isn't quite 45 degrees but that shouldn't really matter I don't think.
Now, in order to find out the vertical 'centre' for collision purposes, I'm doing the following:
Find out where the sprite is in relation to the X Coordinate of the tile. (So, if the tile is at 100 and the sprite is at 110, then I am 10 in from the X of the tile.
I then multiply that by my slope (slope being height/width or 100/102 in my case)
I then divide by 2 to get the centre
Finally, I subtract that result from the height of the tile (to invert it)
This gives me the vertical center which I can compare with the centre of my sprite to check for collision.
So, my code looks like this:
VertTileCentre=Math.round(tileYCoord]+tile.quadHeight-((slope*(spriteX-tileX))/2));
Results
When I run this, although my sprite can slide up and down the slope it doesn't follow the (visible) path of my tile so I get something like this:
So when moving down the slope it moves in a jagged line and when trying to move up, it moves up the slope until it hits the next tile along, then gets stuck
Would appreciate if someone could point out why my sprite path is not following the slope correctly or anything else I may be doing incorrectly.
Edit 1 - results from further experimenting
I've noticed that the sprite when at the top-left of a slope tile sinks into the tile slightly, this is why the sprite was 'getting stuck' when moving up - because it was hitting solid blocks behind (which have their own collision detection)
Strangely, I've also noticed that if I remove the 'divide by 2' from my above calculations the path of the sprite is pretty much OK although the sprite itself still sinks into the tile slightly (But now throughout the whole slope) - therefore if I remove the solid blocks, it works OK.
So I have no idea why not dividing by 2 makes sense and also why my sprite is not correctly sitting on the slope!!