废话不多说,想上代码
完整代码:https://github.com/ytbLib/Tank_Battle
/**
* @function 子弹与瓦片的碰撞
* @param bullet 子弹类
* @return {boolean} 如果碰撞,返回true
*/
function bullet_Tile_Collision(bullet) {
var result = false;
var rowIndex = 0; //行索引
var colIndex = 0; //列索引
var tileNum = 0; //击中的瓦片数
//根据子弹的起始坐标判断当前子弹所在瓦片的索引
//不同方向获取索引的方式不同
if (bullet.dir == UP){
rowIndex = parseInt((bullet.y - map.offsetY) / map.tileSize);
colIndex = parseInt((bullet.x - map.offsetX) / map.tileSize);
} else if (bullet.dir == DOWN){
rowIndex = parseInt((bullet.y - map.offsetY + bullet.size) / map.tileSize);
colIndex = parseInt((bullet.x - map.offsetX) / map.tileSize);
} else if (bullet.dir == LEFT){
rowIndex = parseInt((bullet.y - map.offsetY) / map.tileSize);
colIndex = parseInt((bullet.x - map.offsetX) / map.tileSize);
} else if (bullet.dir == RIGHT){
rowIndex = parseInt((bullet.y - map.offsetY) / map.tileSize);
colIndex = parseInt((bullet.x - map.offsetX + bullet.size) / map.tileSize);
}
//当子弹越界时
if (colIndex >= map.tileCountWidth || colIndex < 0 ||
rowIndex >= map.tileCountHeight || colIndex < 0){
return true;
}
//当子弹方向为上或者下时,判断地图列方向应该打掉多少块瓦片
if (bullet.dir == UP || bullet.dir == DOWN){
//子弹右边距距离当前瓦片起始x坐标的宽度
var wBulletInCurTile = parseInt(bullet.x - map.offsetX - (colIndex * map.tileSize) + bullet.size);
//当子弹右边距在瓦片边界时,
if (wBulletInCurTile % map.tileSize == 0){
tileNum = parseInt(wBulletInCurTile / map.tileSize);
} else { //当子弹右边距当前瓦片内部或者超过瓦片时
tileNum = parseInt(wBulletInCurTile / map.tileSize) + 1;
}
for (var i = 0; i < tileNum && colIndex + i < map.tileCountWidth; i++){
var tempTile = map.mapLevel[rowIndex][colIndex + i];
if (tempTile == NORMAL_BRICK || tempTile == DIAMOND_BRICK){
result = true;
if (tempTile == NORMAL_BRICK){
map.mapLevel[rowIndex][colIndex + i] = 0;
} else if (tempTile == DIAMOND_BRICK){
}
}
}
} else if (bullet.dir == LEFT || bullet.dir == RIGHT){
//子弹下边距距离当前瓦片起始y坐标的高度
var hBulletInCurTile = parseInt(bullet.y - map.offsetY - (rowIndex * map.tileSize) + bullet.size);
//当子弹下边距在瓦片边界时,
if (hBulletInCurTile % map.tileSize == 0){
tileNum = parseInt(hBulletInCurTile / map.tileSize);
} else { //当子弹下边距当前瓦片内部或者超过瓦片时
tileNum = parseInt(hBulletInCurTile / map.tileSize) + 1;
}
for (var i = 0; i < tileNum && rowIndex + i < map.tileCountWidth; i++){
var tempTile = map.mapLevel[rowIndex + i][colIndex];
if (tempTile == NORMAL_BRICK || tempTile == DIAMOND_BRICK){
result = true;
if (tempTile == NORMAL_BRICK){
//把当前瓦片清除
map.mapLevel[rowIndex + i][colIndex] = 0;
} else if (tempTile == DIAMOND_BRICK){
}
}
}
}
return result;
};
详解+图解: