Skip to content

Instantly share code, notes, and snippets.

@castaneai
Created May 22, 2014 15:23
Show Gist options
  • Save castaneai/785551a3a9f367498c7d to your computer and use it in GitHub Desktop.
Save castaneai/785551a3a9f367498c7d to your computer and use it in GitHub Desktop.
EaselJSで衝突判定,落下運動
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, 20, 20);
box.setBounds(0, 0, 20, 20);
box.x = 150;
box.y = 0;
stage.addChild(box);
// 障害物
var obss = [];
_.forEach([
{x: 100, y: 100, width: 100, height: 10},
{x: 200, y: 200, width: 100, height: 10}
], function(rect) {
var obs = new createjs.Shape();
obs.graphics.beginFill("black").drawRect(0, 0, rect.width, rect.height);
obs.setBounds(0, 0, rect.width, rect.height);
obs.x = rect.x;
obs.y = rect.y;
obss.push(obs);
});
obss.forEach(function(obs) {
stage.addChild(obs);
});
// ゲームループ
var vy = 0;
createjs.Ticker.setFPS(30);
createjs.Ticker.addEventListener("tick", function() {
// めり込んでいれば速度を0にしてめり込まないように調整する
_.forEach(obss, function(obs) {
var movedPlayerRect = box.getTransformedBounds();
movedPlayerRect.y += vy;
var obsRect = obs.getTransformedBounds();
var dist = getIntersection(movedPlayerRect, obsRect);
if (dist.dx <= 0 && dist.dy <= 0) {
vy += dist.dy;
} else {
vy += 1;
}
});
box.x += 1;
box.y += vy;
stage.update();
});
/**
* 指定した矩形領域の中心座標を求める
*/
function getCenter(rect) {
return {x: rect.x + rect.width / 2, y: rect.y + rect.height / 2};
}
/**
* 2つのDisplayObjectの
* 衝突判定をする
* 返り値は2つのオブジェクト間の(x, y)それぞれの距離(dx, dy)
* xまたはyが0以下であれば衝突したといえる
*/
function getIntersection(rect1, rect2) {
var center1 = getCenter(rect1);
var center2 = getCenter(rect2);
return {
dx: Math.abs(center1.x - center2.x) - (rect1.width / 2 + rect2.width / 2),
dy: Math.abs(center1.y - center2.y) - (rect1.height / 2 + rect2.height / 2)
};
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment