Design Lab 5: Game Media   [ Monday 6pm - Rm 908]

instructor: Jonah Warren
email: jonah AT feedtank DOT com
url: http://www.playfulsystems.com/teaching/2006/gamemedia


All of the following programs have the following structure:

Hit Test Problem
[ Download the FLA ]
stop();

onEnterFrame = function() {
	if (!guy.hitTest(_root.box)) {
		if(Key.isDown(Key.RIGHT)) {
			guy._x += 5;
		}
		if (Key.isDown(Key.LEFT)) {
			guy._x -= 5;
		}
		if(Key.isDown(Key.UP)) {
			guy._y -= 5;
		}
		if (Key.isDown(Key.DOWN)) {
			guy._y += 5;
		}
	}
}


[ First click inside the rectangle, then press the left, right, up and down arrow keys ]


Hit Test Solution 1
[ Download the FLA ]
stop();

onEnterFrame = function() {
    var oldXPos = guy._x;
	var oldYPos = guy._y;

	if(Key.isDown(Key.RIGHT)) {
		guy._x += 5;
	}
	if (Key.isDown(Key.LEFT)) {
		guy._x -= 5;
	}
	if(Key.isDown(Key.UP)) {
		guy._y -= 5;
	}
	if (Key.isDown(Key.DOWN)) {
		guy._y += 5;
	}

	if (guy.hitTest(box))  {
		guy._x = oldXPos;
		guy._y = oldYPos;
	}

}


[ First click inside the rectangle, then press the left, right, up and down arrow keys ]


Hit Test Solution 2
[ Download the FLA ]
stop();

onEnterFrame = function() {

    if(Key.isDown(Key.RIGHT)) {
		guy._x += 5;
		if (guy.hitTest(box)) guy._x = box._x - guy._width - 1;
	}
	if (Key.isDown(Key.LEFT)) {
		guy._x -= 5;
		if (guy.hitTest(box)) guy._x = box._x + box._width + 1;
	}
	if(Key.isDown(Key.UP)) {
		guy._y -= 5;
		if (guy.hitTest(box)) guy._y = box._y + box._height + 1;
	}
	if (Key.isDown(Key.DOWN)) {
		guy._y += 5;
		if (guy.hitTest(box)) guy._y = box._y - guy._height - 1;
	}

}


[ First click inside the rectangle, then press the left, right, up and down arrow keys ]


Hit Test Solution 3
[ Download the FLA ]
stop();

onEnterFrame = function() {

	if(Key.isDown(Key.RIGHT)) {
		guy._x += speed;
		if (isHit(guy, box)) guy._x = box._x - guy._width;
	}
	if (Key.isDown(Key.LEFT)) {
		guy._x -= speed;
		if (isHit(guy, box)) guy._x = box._x + box._width;
	}
	if(Key.isDown(Key.UP)) {
		guy._y -= speed;
		if (isHit(guy, box)) guy._y = box._y + box._height;
	}
	if (Key.isDown(Key.DOWN)) {
		guy._y += speed;
		if (isHit(guy, box)) guy._y = box._y - guy._height;
	}

}

function isHit(mc1:MovieClip, mc2:MovieClip):Boolean {
	// "yMax", "yMin", "xMax", "xMin"
	var bounds_obj1:Object = mc1.getBounds(this);
	var bounds_obj2:Object = mc2.getBounds(this);

	if ((bounds_obj1["xMax"] > bounds_obj2["xMin"] && bounds_obj1["xMin"] < bounds_obj2["xMax"] ) && (bounds_obj1["yMax"] > bounds_obj2["yMin"] && bounds_obj1["yMin"] < bounds_obj2["yMax"])) return true;
	return false;
}


[ First click inside the rectangle, then press the left, right, up and down arrow keys ]