【问题标题】:Moving the same circle at the same time independently javascript? [closed]在同一时间独立移动同一个圆圈javascript? [关闭]
【发布时间】:2016-01-21 06:07:59
【问题描述】:

我正在使用 html 和 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>

【问题讨论】:

    标签: javascript html canvas


    【解决方案1】:

    由于它们共享 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>

    【讨论】:

    • 我会怎么做,我尝试了一个数组,但我失败了你的建议
    • 取决于你想去的复杂程度,以及圈子需要做什么。我只是在我的 sn-p 中随机化了 x 和 y,但是您可以创建一个圆形对象,并且每个对象都将坐标作为它们的属性。如果您要为多个圆圈等设置动画,那么这就是您理想的做法。
    • 很久以前,我写了一个与您的问题不相似的答案,但实际的解决方案可能会对您有所帮助,请在此处查看:stackoverflow.com/a/34265601/965907
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-29
    • 2012-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多