在阅读了视野算法之后,我决定自己为我正在开发的游戏创建一个。几个小时后,我想出了以下脚本:
function CalculateFOV() {
ClearFOV();
map[player.x][player.y].light = 100;
var open = new Array();
var closed = new Array();
sourceNeighbors = map[player.x][player.y].neighbors;
for(var i = 0;i<sourceNeighbors.length;i++) {
open.push(sourceNeighbors[i]);
}
while(open.length > 0) {
var curTile = open[0];
var highestLightValue = 0;
for(j in curTile.neighbors) {
if(curTile.neighbors[j].light > highestLightValue) {
highestLightValue = neighbors[j];
}
}
curTile.light = highestLightValue-10;
if(curTile.light > 10) {
for(var j = 0;j<curTile.neighbors.length;j++) {
var addCell = true;
if(FindValue(closed, open[0].neighbors[j])) addCell = false;
if(addCell) {
open.push(neighbors[j]);
}
}
}
closed.push(curTile);
open.shift();
}
}
function ClearFOV() {
for(var x = 0;x<mapSizeX;x++) {
for(var y = 0;y<mapSizeY;y++) {
map[x][y].lightValue = 0;
}
}
}
function FindValue(list, value) {
for(var i = 0;i<list.length;i++) {
if(list[i] == value) {
return true;
}
}
return false;
}
它应该从一个光源向外传播一个光值,随着它的传播而减少。它使用已被赋予光值的瓦片的封闭列表,以避免多次击中单个单元格。从理论上讲,这应该会大大提高效率。
不幸的是,它似乎有一个错误,也许不止一个。我疲惫的大脑无法找到它(或它们),所以我非常感谢一些帮助。它甚至有意义吗?
此外,如果您可能需要它,这里是 Tile 类:
function Tile(x,y,character, thisMap, blocked, blockSight) {
this.x = x;
this.y = y;
this.character = character;
this.blocked = blocked;
this.blockSight = blockSight;
this.lightValue = 25;
this.neighbors = new Array();
}
Tile.prototype = {
create: function(blocked, blockSight, character) {
this.blocked = blocked;
this.blockSight = blockSight;
this.character = character;
var rockTile = RandomRange(1,4);
var rockTileStr = "rock"+rockTile;
},
draw: function() {
var id = '#t' + this.x + '_' + this.y;
var lightColor = this.lightValue/100;
$(id).css("opacity", lightColor);
},
assign: function() {
var north = this.x-1;
var south = this.x+1;
var east = this.y+1;
var west = this.y-1;
if(north >= 0 && south <= mapSizeX && west >= 0 && east <= mapSizeY) {
//1st: we add the northwest neighbor.
// *|/
// -#-
// /|\
this.neighbors[0] = map[north][west];
//2nd: we add the north neighbor.
// \*/
// -#-
// /|\
this.neighbors[1] = map[north][this.y];
//3rd: we add the northeast neighbor.
// \|*
// -#-
// /|\
this.neighbors[2] = map[north][east];
//4th: we add the east neighbor.
// \|/
// -#*
// /|\
this.neighbors[3] = map[this.x][east];
//5th: we add the southeast neighbor.
// \|/
// -#-
// /|*
this.neighbors[4] = map[south][east];
//6th: we add the south neighbor.
// \|/
// -#-
// /*\
this.neighbors[5] = map[south][this.y];
//7th: we add the southwest neighbor.
// \|/
// -#-
// *|\
this.neighbors[6] = map[south][west];
//8th: we add the west neighbor.
// \|/
// *#-
// /|\
this.neighbors[7] = map[this.x][west];
}
},
}
谢谢,并为发布这么长的问题道歉;我只是现在不知道还能去哪里。