When I started out with flash, which was not too long ago, I could not figure out a working hitTest code. I finally discovered a fairly simple way to have hitTest codes in a game. I looked all over the internet and all I could find having to do with hitTest was detecting it, not responding. I found a few good tutorials on how to make a response after two objects hit, but they could always cut corners.
Now, I will spoil you. There is a very simple explanation of this. we all know there are 4 main points of a rectangle, its corner points. If neither of those are touching an object, it can move. If a point is touching something, its path is being blocked. All you have to establish is which points belong to which direction and what the coordinates of the points are. Here is some code for a 80*80 square called “guy” and its response to “ground”.
function onLoad() {
//define variables
//a is the top left corner of guy
/* a=_root.guy._x-30, _root.guy._y-30;
b is the bottom left corner of guy
b=_root.guy._x-30, _root.guy._y+30;
c is the bottom right corner of guy
c=_root.guy._x+30, _root.guy._y+30;
d is the rop right corner of guy
*/ d=_root.guy._x+30, _root.guy._y-30;
//5 pixels every frame
speed = 5;
}
function onEnterFrame() {
//if the Right key is pressed and point d and point c are not touching ground, then move
if (Key.isDown(Key.RIGHT) && !_root.ground.hitTest(_root.guy._x+30+speed, _root.guy._y-30, true) && !_root.ground.hitTest(_root.guy._x+30+speed, _root.guy._y+30, true)) {
_root.guy._x += speed;
}
//if the Left key is pressed and point a and point b are not touching ground, then move
if (Key.isDown(Key.LEFT) && !_root.ground.hitTest(_root.guy._x-30-speed, _root.guy._y-30, true) && !_root.ground.hitTest(_root.guy._x-30-speed, _root.guy._y+30, true)) {
_root.guy._x -= speed;
}
//if the Up key is pressed and point d and point a are not touching ground, then move
if (Key.isDown(Key.UP) && !_root.ground.hitTest(_root.guy._x+30, _root.guy._y-30-speed, true) && !_root.ground.hitTest(_root.guy._x-30, _root.guy._y-30-speed, true)) {
_root.guy._y -= speed;
}
//if the Down key is pressed and point b and point c are not touching ground, then move
if (Key.isDown(Key.DOWN) && !_root.ground.hitTest(_root.guy._x-30, _root.guy._y+30+speed, true) && !_root.ground.hitTest(_root.guy._x+30, _root.guy._y+30+speed, true)) {
_root.guy._y += speed;
}
}
I defined the points in the variable section so that you can get a more visual feel of this. I reccommend using this in basic actionscript but there are probably better, quicker ways to do this. Thanks.
----Ryan