【发布时间】:2015-04-05 14:42:24
【问题描述】:
我的项目是创建一个游戏,球应该在按键上跳跃,左右移动。我的问题是,我在该游戏中实施的重力给我带来了问题。球卡在地上,这是我画布底部的图片。我猜是因为错误的碰撞代码而卡住了。
问题是,如果您能帮助我解决这个问题,或许可以提示如何继续,因为我试图找出导致该问题的碰撞,但我一无所获。
该游戏的链接在这里:Game JSFiddle:Fiddle
玩家碰撞所在的代码/其他代码正在正常工作,所以我不会把它们放在这里,只有当你真的需要它们时/
function Player(x, y) {
var size = 70;
GameObject.call(this, x, y, size);
this.img = document.getElementById("lopta");
this.rotation = 0;
this.dx = Math.random() * 50 - 25;
this.dy = Math.random() * 50 - 25;
}
// Dedi vlastnosti z GameObject
Player.prototype = Object.create(GameObject.prototype);
Player.prototype.move = function(dt) {
var x = this.x;
var y = this.y;
var sirka = canvas.width;
var vyska = canvas.height;
var bounce = 0.6;
// Gravitacia
this.dy += 9.8 * dt;
// Posun
if ( keys[37] ) {
this.rotation -= dt;
x-=5;
}
if ( keys[39] ) {
this.rotation += dt;
x+=5;
}
if ( keys[38] ) y-=5;
if ( keys[40] ) y+=5;
// Test novej pozicie
var collision = false;
for (i in scene) {
var obj = scene[i];
var test =
x -35>= obj.x + obj.size ||
x + this.size -35<= obj.x ||
y -35>= obj.y + obj.size ||
this.dy - 35 >= obj.dy + obj.size ||
y + this.size -35 <= obj.y ||
this.dy + this.size -35<= obj.dy;
if (!test) {
collision = true;
break;
}
}
// Posun bez kolizie
if (!collision) {
this.x = x;
this.y = y;
}
// Posun
//this.x += this.dx * dt;
this.y += this.dy * dt;
// podmienky aby lopta nevysla z hracieho pola cize z canvasu
if (this.x + this.size - 35> canvas.width) {
this.x = canvas.width - this.size +35;
}
if (this.x -35 < 0) {
this.x = 35;
}
if (this.y+this.size - 35 > canvas.height) {
this.y = canvas.height - this.size + 35;
this.dy *= -bounce;
if(this.dy * (-bounce) < 4)
this.dy = 0;
}
if (this.y - 35< 0) {
this.y = 35;
};
};
Player.prototype.draw = function() {
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.rotation);
ctx.translate(-35, -35);
//ctx.scale(this.size,this.size);
ctx.drawImage(this.img, 0, 0, this.size, this.size);
ctx.restore();
};
【问题讨论】:
-
如果你创建一个有效的jsfiddle.net,它会有所帮助。
-
我试过了,但是有更多文件,我不知道如何将它们全部添加到一起,所以它会起作用。
-
左边有外部资源选项,也可以hack the CSS pane。
-
用外部资源更新,见上文:)
标签: javascript html canvas gravity