我很難理解本教程。 https://www.youtube.com/watch?v=F2Dc-JlwgN4。請幫我理解html5遊戲的代碼
<canvas id="ctx" width="500" height="500" style="border:1px solid #000000"></canvas>
<script>
var ctx = document.getElementById("ctx").getContext("2d");
ctx.font = '30px Arial';
var height = 500;
var width = 500;
var message = "bouncing";
var player = {
x:50,
speedX:30,
y: 40,
speedY: 5,
name: "P",
};
function getDistanceBetweenEntity(entity1, entity2){
var vx = entity1.x - entity2.x;
var vy = entity1.y - entity2.y;
return Math.sqrt (vx*vx+vy*vy);
}
function testCollisionEntity(entity1, entity2){
var distance = getDistanceBetweenEntity(entity1, entity2);
return distance < 30;
}
var enemyList = {};
enemey("E1", 150, 350, 10, 15, "E1");
enemey("E2", 250, 350, 10, -15, "E2");
function enemey(id,x,y,speedX,speedY, name) {
var enemy2 = {
x: x,
speedX:speedX,
y: y,
speedY: speedY,
name: name,
id:id,
};
enemyList[id] = enemy2;
}
setInterval(update,40);
function updateEntity(something){
something.x += something.speedX;
something.y += something.speedY;
ctx.fillText(something.name, something.x, something.y);
if (something.x < 0 || something.x > width) {
console.log(message);
something.speedX =- something.speedX;
}
if (something.y < 0 || something.y > height) {
console.log(message);
something.speedY =- something.speedY;
}
};
function update() {
ctx.clearRect(0,0,height,width);
for (var i in enemyList) {
updateEntity(enemyList[i]);
var isColliding = testCollisionEntity(player, enemyList[i]);
if (isColliding){
console.log('colliding!')
}
}
updateEntity(player);
}
</script>
這裏是的jsfiddle鏈接 http://jsfiddle.net/sinner019/0k9cnLce/
我不明白如何將這個拖參數使用實體和ENTITY2作品。你能幫我理解嗎?
這簡直是畢達哥拉斯,得到距離的2點之間的X和Y的變化,並返回斜邊,你到底還不明白嗎? – juvian
它正在計算直角三角形的[斜邊](http://en.wikipedia.org/wiki/Hypotenuse)的長度,該直角三角形相當於計算2d笛卡爾座標系上兩點之間的距離。 – Shashank
我不能理解哪個值傳遞給entity1和entity2。請看完整的代碼http://jsfiddle.net/sinner019/0k9cnLce/ – Shuvo