Skip to content

Instantly share code, notes, and snippets.

@castaneai
Last active August 31, 2020 10:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save castaneai/5130989875a48de5e5b2 to your computer and use it in GitHub Desktop.
Save castaneai/5130989875a48de5e5b2 to your computer and use it in GitHub Desktop.
detecting collisions between two DisplayObjects with EaselJS (CreateJS)
window.onload = function() {
// 初期設定
var canvas = document.createElement("canvas");
canvas.width = 500;
canvas.height = 250;
document.body.appendChild(canvas);
var stage = new createjs.Stage(canvas);
// 追従する箱
var box = new createjs.Shape();
box.graphics.beginFill("red").drawRect(0, 0, 50, 50);
// Shapeは自動的にBoundsを作ってくれないので、自分でsetBoundsする必要がある
box.setBounds(0, 0, 50, 50);
stage.addChild(box);
// 障害物
var obs = new createjs.Shape();
obs.graphics.beginFill("black").drawRect(0, 0, 100, 10);
obs.setBounds(0, 0, 100, 10);
obs.x = obs.y = 100;
stage.addChild(obs);
// ゲームループ
createjs.Ticker.setFPS(30);
createjs.Ticker.addEventListener("tick", function() {
box.x = stage.mouseX - box.getBounds().width / 2;
box.y = stage.mouseY - box.getBounds().height / 2;
box.alpha = checkCollision(box, obs) ? 0.5 : 1.0;
stage.update();
});
/**
* 2つのDisplayObjectの
* 衝突判定
*/
function checkCollision(obj1, obj2) {
// getBoundsは各objのローカル座標なので、他の座標系と比較できない
// よって、getTransformedBounds()で親の座標系から見た座標に
// 変換したものを受け取ればOK
var rect1 = obj1.getTransformedBounds();
var rect2 = obj2.getTransformedBounds();
if (rect1.x > rect2.x + rect2.width ||
rect1.y > rect2.y + rect2.height ||
rect2.x > rect1.x + rect1.width ||
rect2.y > rect1.y + rect1.height) {
return false;
} else {
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment