是什么问题?addBall()若放在gameloop()中小球会出现,但小球数量不是10个,放在init()中,小球又不出现。
我实在很头大。
document.body.onload=game;
var ball=[];
function init(){
addBall();
}
function game(){
init();
lastTime=Date.now();
delTime=0;
gameLoop();
}
function gameLoop(){
window.requestAnimationFrame(gameLoop);//循环调用
var now = Date.now();
delTime = now-lastTime;
lastTime=now;
if(delTime > 40){delTime = 40;}
drawBall(context2);
updateBall(canvasW,canvasH);
}
function addBall () {
for (var i = 0; i < 10; i++) {
var R = Math.floor(Math.random() * 255);
var G = Math.floor(Math.random() * 255);
var B = Math.floor(Math.random() * 255);
var radius = Math.random() * 10 + 20;
var aBall = {
x: Math.random() * (800 - 2 * radius) + radius * 2,
y: Math.random() * (600 - 2 * radius) + radius * 2,
r: radius,
color: 'rgb(' + R + ',' + G + ',' + B + ')',
vx: Math.pow(-1, Math.random() * 100) * (Math.random() * 1.5 + 0.5),
vy: Math.pow(-1, Math.random() * 100) * (Math.random() * 1.5 + 0.5)
};
ball.push(aBall);
}
}
function drawBall (cxt) {
cxt.clearRect(0,0,canvasW,canvasH);
for (var i = 0; i < ball.length; i++) {
cxt.fillStyle = ball[i].color;
cxt.globalAlpha = 0.6;
cxt.beginPath();
cxt.arc(ball[i].x,ball[i].y,ball[i].r,0,2*Math.PI);
cxt.closePath();
cxt.fill();
}
}
function updateBall (canW,canH) {
for(var i=0;i<ball.length;i++){
ball[i].x += ball[i].vx * delTime * 0.003;
ball[i].y += ball[i].vy * delTime * 0.003;
if(ball[i].x - ball[i].r <= 0 ){
//this.vx[i] = -this.vx[i];
ball[i].x = ball[i].r;
}
if(ball[i].x + ball[i].r >= canW ){
ball[i].vx = -ball[i].vx;
ball[i].x = canW - ball[i].r;
}
if(ball[i].y - ball[i].r <= 0 ){
//this.vy[i] = -this.vy[i];
ball[i].y = ball[i].r;
}
if(ball[i].y + ball[i].r >= canH ){
ball[i].vy = -ball[i].vy;
ball[i].y = canH - ball[i].r;
}
}
}
添加回答
举报
0/150
提交
取消