I'm making a somewhat simple side-scroller in Flash. The way I'm currently doing the really basic physics(you don't fall through floors/can't walk through walls) is that I have a big symbol of all the walls/floor/ceiling and use some complex hit testing against that.
Basically, if you are moving down when you hit, move you up til you're out, moving left move right, etc. If you're moving diagonally you'll move diagonally out and then move over the direction that didn't get you out until you hit something or get lined up. Then I move you down one so you're touching the floor since I have you fall down 20 pixels if you're in the air, and that make it slow since it has to do 20 hit tests every frame. Here's the code I use:
public function onEnterFrame(e:Event){ hitTests = 0; trace("x:"+x+", y: "+y); if(!game.main.Paused) { if(!HitTest.complexHitTestObject(this, room.main.currentRoom.edge, 1)) { hitTests++; movementY += 10; // trace("movY: "+(movementY-20)+" > "+movementY); } if(game.main.Ahit) { movementX -= 5; } if(game.main.Dhit) { movementX += 5; } x += movementX; y += movementY; // trace((y-movementY)+" + "+movementY+" = "+y); if(HitTest.complexHitTestObject(this, room.main.currentRoom.edge, 1)) { hitTests++; dynamicXnum = 0; dynamicYnum = 0; free4floor = true; while(HitTest.complexHitTestObject(this, room.main.currentRoom.edge, 1)) { hitTests++; if(movementX == 0 && movementY == 0) { break; xlast = undefined; } if(movementX > 0) { x--; dynamicXnum--; } if(movementX 0 || free4floor) { y--; dynamicYnum--; free4floor = false; } if(movementY 0) { y--; dynamicYnum--; } else { break; } } } if(xlast == false) { while(!HitTest.complexHitTestObject(this, room.main.currentRoom.edge, 1) && dynamicXnum != 0) { hitTests++; if(dynamicXnum 0) { x--; dynamicXnum--; } else { break; } } if(movementX > 0) x--; if(movementX 0 || movementX != 0) y++; movementY = 0; } } if(movementX >= 5) { movementX -= 5; } else if(movementX maxHitTests) maxHitTests = hitTests; trace("end: x:"+x+", y: "+y); trace("hts: "+hitTests) trace("mhts: "+maxHitTests); } }
This is working okay for now, and you can see a demo of it here, but there are a couple of problems.
For one, it can get a little slow, but this isn't that big of a problem, since it's pretty rare, and it's not that slow. Mainly, it's that when I get around to animating the little dude, and even now sometimes when it messes up a bit, it will get more than five pixels in the wall. Then when I try to move out, it won't make it out in one frame, and it will force him through the wall the wrong way, making him fall into infinity...does anyone know how to fix this? Should I totally redo how I do it? Should I have some kind of variable for which way he came from? If so, how should I do it?