Pixel Perfect Collision Detection AS3


/ Published in: ActionScript 3
Save to your folder(s)

A fast and accurate Hit Test that can check if objects truly touch each other.
This differs from HitTestObject, as it actually checks if objects visually hit, rather then their boundary boxes. Include this function in your code, for easy, efficient and effortless collision detection!


Copy this code and paste it in your HTML
  1. /*
  2. Created by Sam Kantor
  3. Example Usage:
  4. if (ObjectsHit(myobject, myotherobject)) {
  5. The Objects hit!
  6. }
  7. */
  8. function ObjectsHit(mc1, mc2):Boolean {
  9. var mc1bounds = mc1.getBounds(this);
  10. var mc2bounds = mc2.getBounds(this);
  11. var allintersections = (mc2bounds.intersection(mc1bounds));
  12. for (var xval:Number = allintersections.x; xval < allintersections.x + allintersections.width; xval ++ ) {
  13. for (var yval:Number = allintersections.y; yval < allintersections.y + allintersections.height;yval ++ ) {
  14. if (mc2.hitTestPoint(xval, yval, true) && mc1.hitTestPoint(xval, yval, true)) {
  15. return(true);
  16. }
  17. }
  18. }
  19.  
  20. return(false);

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.