我对编程很新,但我设法制作了一个带有碰撞的瓷砖地图系统。我正在寻找有关优化的提示,或者如果我这样做的方式完全是愚蠢的,请让我知道更好的方法。
https://jsfiddle.net/19ed4sm0/
基本上我创建了一个循环遍历map数组的函数,并在每次移动键时调用。该系统采用8方向运动,这是我想保留的。
//Collision with map tiles
function checkMove(px, py, pw, ph, pd) {
for(var y=0; y < map.length; y+=1) {
for(var x=0; x <map[y].length; x+=1) {
var tileX = x * 32;
var tileY = y * 32;
if (map[y][x] === 1) {
if (px < tileX+32 && px + pw > tileX && py < tileY+32 && py + ph > tileY) {
if (pd === 'right' && px+pw > tileX) {
_player.x = tileX - pw - _player.speed;
}
if (pd === 'left' && px < tileX+32) {
_player.x = tileX+32 + _player.speed;
}
if (pd === 'up' && py+ph > tileY) {
_player.y = tileY + ph + _player.speed;
}
if (pd === 'down' && py < tileY+32) {
_player.y = tileY-32 - _player.speed;
}
}
}
}
}
}
function playerInit() {
this.width = 32;
this.height = 32;
this.x = cWidth/2-16;
this.y = cHeight-96;
this.speed = 4;
this.gravity = 6;
this.color = '#ffb5e2'
this.update = function() {
//movement
if (keydown.up === true) {
checkMove(this.x, this.y - this.speed, tileSize, tileSize, 'up');
this.y -= this.speed;
}
if (keydown.left === true) {
checkMove(this.x-this.speed, this.y, tileSize, tileSize, 'left');
this.x -= this.speed;
}
if (keydown.right === true) {
checkMove(this.x+this.speed, this.y, tileSize, tileSize, 'right');
this.x += this.speed;
}
if (keydown.down === true) {
checkMove(this.x, this.y+this.speed, tileSize, tileSize, 'down');
this.y += this.speed;
}
//canvas border collision
if (this.x < 0) {
this.x = 0;
}
if (this.y < 0) {
this.y = 0;
}
if (this.x > cWidth - this.width) {
this.x = cWidth - this.width;
}
if (this.y > cHeight - this.height) {
this.y = cHeight - this.height;
}
}
this.render = function() {
c.fillStyle = this.color;
c.fillRect(this.x, this.y, this.width, this.height);
}
}
答案 0 :(得分:1)
实际上你只需要检查当前位置周围的8个瓦片。
要计算下一个位置,您可以将其偏移量存储在数组中:
var deltaX = [-1, -1, -1, 0, 0, 1, 1, 1];
var deltaX = [-1, 0, 1, -1, 1, -1, 0, 1];
for (var i = 0; i < deltaX.length; i++) {
var nextX = tileX + deltaX[i];
var nextY = tileY + deltaY[i];
// check collisions here
}
现在,您只需检查 8 切片是否存在碰撞,而不是检查 20 * 20 = 400 切片。
答案 1 :(得分:0)