2015-08-27 87 views
0

我試圖添加火花到我的基本乒乓遊戲。無論什麼時候球擊中槳,都應該添加閃光燈。我與帆布乒乓閃閃發光

function create_sparks(x, y, m) { 
    this.x = x; 
    this.y = y; 
    this.r = 1,2; 
    this.vx = -1.5 + Math.random() * 3; 
    this.vy = m * Math.random() * 1.5; 
} 

IM產生火花的物體像這樣

if (flag == 1) { 
     for (var j = 0; j < 20; j++) { 

      particles.push(new create_sparks(spark.x, spark.y, mult)); 
     } 
    } 
    emitspark(); 
    flag = 0; 

標誌爲1時,球擊中水坑,spark.x和spark.y是的源創建它們球(其中它撞擊坑)和finaly IM動畫他們這樣

function emitspark() { 
    for (var i = 0; i < particles.length; i++) { 
     var p = particles[i]; 
     ctx.beginPath(); 
     ctx.fillStyle = "white"; 
     if (p.r > 0) { 
      ctx.arc(p.x, p.y, p.r, 0, Math.Pi * 2); 
     } 
     ctx.fill(); 
     p.x+=p.vx; 
     p.y+=p.vy; 
     p.r=Math.max(p.r-0.05,0.0); 
    } 
} 

問題是,火花不會露面,也沒有代碼拋出的任何錯誤,並正常工作(只是沒有火花)沒有我忽視了一些事情? here 是演示

+0

嘗試記住每次迭代後關閉路徑ctx.closePath(); –

+0

您正在嘗試訪問'ball.h',但'ball'沒有爲其設置任何變量'h'。 –

+0

球的製圖工作正常,即時通訊談論火花 – Darlyn

回答

1

主要問題是ball.h未定義 - 它爲spark.y值生成一個NaN值。

ball = { 
    x: 50, 
    y: 50, 
    r: 5, 
    h: 10, // < ---- NEW 
    c: "white", 
    vx: 4, 
    vy: 8, 

    // Function for drawing ball on canvas 
    draw: function() { 
     ctx.beginPath(); 
     ctx.fillStyle = this.c; 
     ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false); 
     ctx.fill(); 
     update(); 
    } 
}; 

修正了這個問題。我還在探索代碼時更改了emitspark()。簡化隨你的便,但這個版本爲我工作:

function emitspark() { 
    for (var i = 0; i < particles.length; i++) { 
     var p = particles[i]; 
      ctx.beginPath(); 
      ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2, true); 
      ctx.lineWidth = 15; 
      ctx.strokeStyle = 'red'; 
      ctx.fillStyle="white"; 
      ctx.fill(); 
      ctx.stroke(); 
     p.x+=p.vx; 
     p.y+=p.vy; 
     p.r=Math.max(p.r-0.05,0.0); 
    } 
} 

最後我建議粒子數組的長度設置爲零,一旦火花效果在防止陣列越來越長。零半徑火花仍在處理中 - 假定上下文弧方法不會爲它們創建路徑。但好閃閃發光!