2012-03-27 49 views
4

我正试图在使用拼贴替换的HTML5/JavaScript游戏中实现照明效果。我现在拥有的是一种有效的工作方式,但是随着光源的移动,过渡看起来不够光滑/自然。这里是我现在的位置:在HTML5/JavaScript游戏中使用拼贴创建平滑照明转换

  1. 现在我有一个背景地图,它有一个光/阴影光谱PNG tilesheet应用到它 - 从最黑暗的瓷砖到完全透明。默认情况下,最黑暗的瓷砖在启动时在整个关卡上绘制,覆盖所有其他层等。
  2. 我使用我预先设定的瓷砖尺寸(40 x 40px)来计算每个瓷砖的位置并存储其x和y坐标在一个数组中。
  3. 我则数组
  4. 我使用的发动机中在每个位置生成一个透明40×40像素“网格块”实体([ImpactJS] [1])然后让我从计算距离我的光源实体到此网格块实体的每个实例。
  5. 我可以用适当的透明度的瓷砖替换那些网格块瓷砖下面的瓷砖。

目前我正在做这样的计算中,其在地图上催生了网格块实体的每个实例:

var dist = this.distanceTo(ig.game.player); 

var percentage = 100 * dist/960; 

if (percentage < 2) { 
    // Spawns tile 64 of the shadow spectrum tilesheet at the specified position 
    ig.game.backgroundMaps[2].setTile(this.pos.x, this.pos.y, 64); 
} else if (percentage < 4) { 
    ig.game.backgroundMaps[2].setTile(this.pos.x, this.pos.y, 63); 
} else if (percentage < 6) { 
    ig.game.backgroundMaps[2].setTile(this.pos.x, this.pos.y, 62); 
}  

(抱歉怪异的间距,我还没忘了粘贴代码在这里正确挂起)

问题是,就像我说的,这种类型的计算不会使光源看起来很自然。瓷砖切换看起来非常尖锐,而理想情况下,他们会使用光谱瓷砖平滑地淡入淡出(我从其他游戏中复制瓷砖来管理这种情况,所以我知道这不是瓷砖阴影的问题,我只是不确定其他游戏如何做)。我在想,也许我用百分比来切换瓦片的方法可以用一种更好/更动态的接近度公式替代,这样可以实现更平滑的过渡?可能任何人有任何想法,我可以做些什么来改善这里的视觉效果,或者用我收集的关于每块瓷砖的信息来计算邻近度的更好方法?

+1

自然光强度成反比来自光源的距离的平方。顺便说一句,这听起来像是一个问题http://gamedev.stackexchange.com/。 – 2012-03-27 08:42:25

+0

你有没有现在的例子?也许简化,也许在[jsfiddle](http://jsfiddle.net/)? – 2012-03-29 15:38:38

回答

0
var size = 32; 
var a = [size]; 

for (i = 0; i < size; i++) { 
    a[i] = [size]; 
    for (y = 0; y < size; y++) { 
     a[i][y] = 1; 
    } 
} 

function display(arr) { 
    h = ""; 
    for (y = 0; y < size; y++) { 
     for (x = 0; x < size; x++) { 
      h += "<span style='background-color:rgba(255,255,255," + (arr[x][y]/10) + ")'></span>"; 
      if (x == size - 1) { 
       h += "<br/>"; 
      } 
     } 
    } 
    $("#h").html(h); 
} 

function LightSource(x, y, l) { 
    this.x = x; 
    this.y = y; 
    this.l = l; 
} 

var ls = []; 
ls.push(new LightSource(6, 6, 4)); 
ls.push(new LightSource(2, 2, 3)); 
ls.push(new LightSource(9, 9, 5)); 
ls.push(new LightSource(20, 14, 8)); 
ls.push(new LightSource(20, 19, 8)); 

for (z = 0; z < ls.length; z++) { 
    for (x = 0; x < size; x++) { 
     for (y = 0; y < size; y++) { 
      xd = x - ls[z].x; 
      yd = y - ls[z].y; 
      dist = Math.sqrt(xd * xd + yd * yd); 
      if (ls[z].l - dist > 0) { 
       a[x][y] += ((10 - a[x][y])/10) * (ls[z].l - dist); 
      } 
     } 
    } 
} 

display(a);​ 

https://gamedev.stackexchange.com/questions/23454/grid-cell-based-light-system

http://jsfiddle.net/ZmPqL/

http://jsfiddle.net/vCgeM/