I've currently written a small platform test demo, but some of the collision detection is causing strange movement problems (teleporting to the tops of blocks, sticking to the sides etc.).
The player is moved every frame using inertia / velocity values, as such:
Player.x += speedX;
Player.y += speedY;
Before the player movement is updated, however, I run a collision check against all blocks in the level. Naturally, in the final version I'll be limiting the number of these checks to only nearby objects, but I need the theory to work first!
When testing collison, I first run a quick exclusion text to see if the player and block are going to intersect:
function WillIntersect(block)
{
var newX = Player.x + speedX;
var newY = Player.y + speedY;
if (Player.x > block.x + block.width || Player.y > block.y + block.height || Player.x + Player.width < clip.x || Player,y + Player.height < clip.y)
{
// no intersection, thus no collision
return false;
}
else
{
// the two object bounding boxes intersect in some way
return true;
}
}
Then, as a result of this check, I then move into a collision detection method that attempts to resolve the collision that occured.
The following rules persist for movement around the game level:
- If no intersection was detected with any object, the speedX and speedY values will remain unmodified.
- If the player falls onto the top of a block, the speedY value is zeroed-out and they are repositioned on top of the block with pixel precision
- If the player hits the underside of a block, the speedY value is zeroed-out and they are repositioned directly underneath the block
- If the player hits the left, or right side of a block, the speedX value is zeroed-out and they are repositioned to the relevant edge.
The problem I have is when a combination of these factors occur. When the player jumps sideways against a wall (or the edge of a platform), the player will 'stick' to the vertical surface because the code generating the 'push to top' or 'push to bottom' check is running and canceling out any other checks.
Video of the effect in question:
http://www.youtube.c...h?v=nFusvi8U_-A
Finally, here's the code I'm currently using for the collisions. I've been tearing my hair out over this for over a week now, and just need some fresh viewpoints - you know what it's like when you've been staring at the same problem for days on end!
function DoCollisions()
{
txtOutput.text = "";
var newX = Player.x + speedX;
var newY = Player.y + speedY;
for (var i = 0; i < Level.numChildren; i++)
{
var clip = Level.getChildAt(i);
if (getQualifiedClassName(clip) == "BLOCK")
{
if (WillIntersect(clip))
{
if (speedX > 0)
{
speedX = 0;
Player.x = clip.x - Player.width;
}
else if (speedX < 0)
{
speedX = 0;
Player.x = clip.x + clip.width;
}
else { }
if (speedY > 0)
{
speedY = 0;
Player.y = clip.y - Player.height;
}
else if (speedY < 0)
{
speedY = 0;
Player.y = clip.y + clip.height;
}
else { }
}
}
}
}
Thanks to anyone who can offer some advice here.