简体   繁体   中英

HitTest in HTML5 Canvas game using Flash CC

I'm working in Flash CC to make a HTML5 Canvas game. However, I can't seem to figure out how to create a hitTest between two movieClips. I found some code on EaselJS web but it doesn't work, or I don't understand how it works.

This is my code in The actions panel:

this.addEventListener("tick",move.bind(this));
function move(){
  if (collision(this.bird, this.bar)){
    this.bird.play(5);
  }
}
function collision(a,b) {
  var locA  = a.globalToLocal(100,0);
  if (b.hitTest(locA.x, locA.y)) { 
    return true; 
  }
}

Ok, so I guess there is no built in functionality for this in Flash or EaselJS yet, so I came up with this and it works ok. But it only checks the hitBox, the rectangular MovieClip boundaries, not the actual visible pixels in the shapes. Frustrating enough, not even width and height are supported properties of a movieclip instance in Flash for HTML5 canvas, so you'll just have to look those up in the properties panel. Anyway, here's what I came up with:

var objA = this.bullet ; // The selected MovieClip
var objA_width = 20; // enter selected Movieclip's width (you can't find out with script, duh!)
var objA_height = 10; // enter selected Movieclip's height

var objB = this.target; // The MovieClip to test collision with
var objB_width = 100; // enter it's width
var objB_height = 100; // ...and it's height


this.addEventListener("tick",hitTest.bind(this));

function hitTest(){
    if (collision(objA, objB, objA_width,objA_height,objB_width,objB_height)){
    //  code to run on collision;
    }
}

var mca = new Object();
var mcb = new Object();

function collision(a,b,aWidth,aHeight,bWidth,bHeight) {
    mca.xr = a.x + (aWidth/2); //the right edge of movieclip A
    mca.xl = a.x - (aWidth/2); //the left edge of movieclip A
    mca.yt = a.y - (aHeight/2); //the top edge of movieclip A
    mca.yb = a.y + (aHeight/2); //the bottom edge of movieclip A

    mcb.xr = b.x + (bWidth/2);
    mcb.xl = b.x - (bWidth/2);
    mcb.yt = b.y - (bHeight/2);
    mcb.yb = b.y + (bHeight/2);

    xHit = mca.xr > mcb.xl && mca.xl < mcb.xr; // returns true if the is any horisontal  overlappnig
    yHit = mca.yt < mcb.yb && mca.yb > mcb.yt; // returns true if the is any vertical overlapping

    if (xHit && yHit){return true;}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM