我正在开发一个简单的游戏,但我卡住了我已经创建了2个方块,你可以移动而另一个应该是无法通行但我无法找到使它成为一个坚实的对象的代码。我需要这个,因为第二个方格将是第一个方块(玩家)将跳上的架子。这只是我遇到这个问题的开始,这个游戏没有接近完成,因为我无法弄清楚如何做到这一点非常感谢。
<!DOCTYPE HTML>
<head>
<title>Something fancy</title>
</head>
<body>
<h3>Arrow keys to move, and space to jump</h3>
<canvas id="canvas"></canvas>
<style>
canvas{border:1px solid black;}
</style>
<script>
(function() {
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
window.requestAnimationFrame = requestAnimationFrame;
})();
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
width = 800,
height = 500,
shelf = {
x : width/20,
y : height - 50,
width : 60,
height : 50
};
player = {
x : width/2,
y : height - 5,
width : 50,
height : 50,
speed: 5,
velX: 0,
velY: 0,
jumping: false
},
keys = [],
friction = 0.8,
gravity = 0.8;
canvas.width = width;
canvas.height = height;
function update(){
// check keys
if (keys[38] || keys[32]) {
// up arrow or space
if(!player.jumping){
player.jumping = true;
player.velY = -player.speed*2;
}
}
if (keys[39]) {
// right arrow
if (player.velX < player.speed) {
player.velX++;
}
}
if (keys[37]) {
// left arrow
if (player.velX > -player.speed) {
player.velX--;
}
}
player.velX *= friction;
player.velY += gravity;
player.x += player.velX;
player.y += player.velY;
if (player.x >= width-player.width) {
player.x = width-player.width;
} else if (player.x <= 0) {
player.x = 0;
}
if(player.y >= height-player.height){
player.y = height - player.height;
player.jumping = false;
}
ctx.clearRect(0,0,width,height);
ctx.fillStyle = " #BA004B";
ctx.fillRect(player.x, player.y, player.width, player.height);
if(createjs.Bitmap.prototype.getBoundingRect == null){
createjs.Bitmap.prototype.getBoundingRect = function(){
return new createjs.Rectangle(
this.x - this.image.width/2,
this.y - this.image.height/2,
this.image.width,
this.image.height);
}
}
if(createjs.Rectangle.prototype.intersects == null){
createjs.Rectangle.prototype.intersects = function(rect){
return (this.x <= rect.x + rect.width &&
rect.x <= this.x + this.width &&
this.y <= rect.y + rect.height &&
rect.y <= this.y + this.height);
}
}
// draw a small red box, which will eventually become our block.
ctx.fillStyle = "red";
ctx.fillRect(shelf.x, shelf.y, shelf.width, shelf.height);
requestAnimationFrame(update);
}
document.body.addEventListener("keydown", function(e) {
keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function(e) {
keys[e.keyCode] = false;
});
window.addEventListener("load",function(){
update();
});
</script>
</body>
&#13;
答案 0 :(得分:1)
您正在讨论的代码是碰撞检测代码。有不同的方法来实现冲突,“正确”的实现将取决于您的游戏需求。
这是一个很好的资源,可以帮助你克服目前的障碍,让你继续前进。只要知道你需要构建一些碰撞检测和解析函数,这些函数会在你引入更多的“可碰撞”对象时运行。
完全过度简化基本碰撞检测:
在每个更新/渲染循环中:
一个。检查您的实体形状是否重叠 湾如果实体不应重叠,请将实体调整回原位。