2016-01-20 68 views
0

我正在使用HTML和JavaScript来制作游戏,而我一直在这一段时间停留在这一段时间这段代码是关于让敌人从屏幕的一侧移动到另一侧不是问题,因为我已经完成了它与其他字符。最大的问题是我无法克隆它们并使它们独立移动。独立javascript的同时移动同一个圆圈?

var canvas = document.getElementById('canvas'); 
 
var h = canvas.height; 
 
var w = canvas.width; 
 
var ctx = canvas.getContext("2d"); 
 
var x = w 
 
var y = Math.floor((Math.random() * 500) + 1); 
 

 
clear(); 
 
circleE(); 
 

 
function clear(){ 
 
    ctx.fillStyle = "Blue" 
 
    ctx.fillRect(0, 0, w, h) 
 
} 
 

 
function circleE(){ 
 
    ctx.fillStyle = "Pink"; 
 
    ctx.beginPath(); 
 
    ctx.arc(x,y,15,0,Math.PI*2,false); 
 
    ctx.closePath(); 
 
    ctx.fill(); 
 
}
<canvas id="canvas" width="1000" height="500" style="border:1px solid #000000;"></canvas>

回答

3

因为它们共享x和y坐标,所有克隆将在完全相同的空间呈现。每个圆圈都需要有自己的坐标。

var canvas = document.getElementById('canvas'); 
 
    var h = canvas.height; 
 
    var w = canvas.width; 
 
    var ctx = canvas.getContext("2d"); 
 

 
    clear(); 
 
    
 
    function clear(){ 
 
     ctx.fillStyle = "Blue" 
 
     ctx.fillRect(0, 0, w, h) 
 
    } 
 

 
    function circleE(){ 
 
     var x = Math.floor((Math.random() * w) + 1); 
 
     var y = Math.floor((Math.random() * h) + 1); 
 
     ctx.fillStyle = "Pink"; 
 
     ctx.beginPath(); 
 
     ctx.arc(x,y,15,0,Math.PI*2,false); 
 
     ctx.closePath(); 
 
     ctx.fill(); 
 
    }
<button onclick="circleE()">Spawn</button><br> 
 
<canvas id="canvas" height="200" width="300"></canvas>

+0

我将如何做到这一点我想一个数组,但我没有什么ü建议 –

+0

你想去多么复杂,什么界需要做的依赖。我只是在我的代码片段中随机化了x和y,但是您可以创建一个圆形对象,并且每个对象都将具有坐标作为其属性。这就是你在为多个圈子设置动画的情况下理想的做法。 – Shomz

+0

很久以前,我为与您不相似的问题写了一个答案,但实际的解决方案可能会帮助您,请参阅此处:http:// stackoverflow.com/a/34265601/965907 – Shomz