私は、太陽のイメージを描き、その周りを地球が周回するイメージを持つスクリプトを書いています。
惑星クラスを次のように定義しました。
function planet(name, size, rotateRate, startx, starty, colour, scale, oRad, oAng, oSpd){//container class for planets
this.name = name;
this.rotateRate = rotateRate;
this.x = startx;
this.y = starty;
this.colour = colour;
this.scale = scale;
this.size = size;
this.orbitRadius= oRad;
this.orbitAngle = oAng;
this.orbitSpeed = oSpd;
this.drawByArc =
function drawArcCircle(){//draws circles using the arc method
context.save();
context.strokeStyle = '#000000';
context.fillStyle = this.colour;
context.lineWidth=3;
context.beginPath();
context.arc(this.x,this.y,this.size*this.scale,0,Math.PI * 2,false)
context.stroke();
context.fill();
context.closePath();
context.restore();
}
}
プログラムでクラスの 2 つのインスタンスを作成し、次の関数を使用してそれらをうまく描画しました。
function gameLoop(){//The Game Loop
var thisTime = Date.now();//current time
var deltaTime = thisTime - lastTime;//find difference, not yet used
update();
draw();
lastTime = thisTime;
setTimeout(gameLoop, 1000/60);
}
function draw(){// Draws all the objects
drawBackground();
Sun.drawByArc();
Earth.drawByArc();
}
function update(){// Updates for animation
//var newRotation = this.getCurrantRotation() + (this.getRotationRate()*deltaTime);
var gSegments;
gScale = 4;
simSpeed = 10;
Sun.scale = gScale;
Earth.scale = gScale;
Earth.orbitSpeed = 360/simSpeed;
//Earth.x = Sun.x + Earth.orbitRadius * Math.cos(Earth.orbitAngle * Math.pi / 180);
//Earth.y = Sun.y - Earth.orbitRadius * Math.sin(Earth.orbitAngle * Math.pi / 180);
}
update メソッドの最後の 2 行をコメント アウトすると、両方の円が正常に描画されますが、最後の 2 行を追加して軌道上の地球の位置を更新しようとすると、Chrome でコードを実行しようとすると、地球の球が表示されます。消える!
Chromeデバッガーにはエラーが表示されないため、エラーが発生する理由がわかりません。
編集::
ちょっとした入力ミス (Math.PI ではなく math.pi) のおかげで、惑星の x と y の値が NaN になっていることがわかりました。
しかし今、私の地球は軌道上で 90 度の位置に留まっており、動かないだけです。