Search code examples
javascriptcreatejseaseljs

EaselJS hitTest on moving bitmaps


I am trying to implement a game where there are moving objects(Bitmaps) and I need to detect collision. I used the following code to make objects move(transform) and check hitTest with mouse hover.

However, the alpha is not changed with the correct mouse position, instead, it detects the left upper corner of the canvas.

enter image description here

rock = new createjs.Bitmap(loader.getResult("rock"));
rock.setTransform(800, 270, 0.5, 0.5);
stage.addChild(rock);
// ..... 

createjs.Ticker.timingMode = createjs.Ticker.RAF;
createjs.Ticker.addEventListener("tick", tick);
// .....

function tick(event) {
    rock.alpha = 0.7;
    if (rock.hitTest(stage.mouseX, stage.mouseY)) {//if hit, change alpha
        rock.alpha = 1;
    }
    var deltaS = event.delta / 1000;
    rock.x = (rock.x - deltaS * groundSpeed);//to gradually shift the rock
    if (rock.x + rock.image.width * rock.scaleX <= 0) {//to re-position the rock
        rock.x = w + Math.random() * 1000;
    }
    stage.update(event);
}

Solution

  • I found the answer when reading the answer to this question.

    Rather than directly getting stage.mouseX or stage.mouseY, the correct position can be obtained using globalToLocal as on this.

      var p = rock.globalToLocal(stage.mouseX, stage.mouseY);
      if (rock.hitTest(p.x, p.y)) {
          rock.alpha = 1;
      }