我正在研究游戏编程,但我在练习中不知所措,但是我无法在更新功能中将这个圆圈停在框的中心。 我做错了什么?
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var circleX = 100;
var circleY = 100;
var circleR = 50;
var circleC = 'yellow';
var circleSpeedX = 65;
var circleSpeedY = 45;
var rectX = 650;
var rectY = 450;
var rectW = 110;
var rectH = 110;
var rectC = 'red';
function clear()
{
context.clearRect(0,0,canvas.width, canvas.height);
}
function drawRect(rectX,rectY,rectW,rectH,rectC)
{
context.fillStyle = rectC;
context.fillRect(rectX,rectY,rectW,rectH);
}
function drawCircle(circleX,circleY,circleR,circleC)
{
context.fillStyle = circleC;
context.beginPath();
context.arc(circleX,circleY,circleR,0,2 * Math.PI);
context.fillStyle = 'orange';
context.fill();
}
function update()
{
}
function draw()
{
clear();
drawRect(0,0,canvas.width,canvas.height,'black');
drawRect(rectX,rectY,rectW,rectH,rectC);
drawCircle(circleX,circleY,circleR,circleC);
}
function loop()
{
update();
draw(rectX, rectY, circleX, circleY);
setTimeout(loop, 30);
}
loop();
答案 0 :(得分:1)
我认为这正是您所寻找的:JSFiddle
HTML:
<div>
<canvas id="myCanvas" height="500" width="500"></canvas>
</div>
JS:
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var circleX = 100;
var circleY = 100;
var circleR = 50;
var circleC = 'yellow';
var circleSpeedX = 6.5;
var circleSpeedY = 4.5;
var rectX = 200;
var rectY = 200;
var rectW = 110;
var rectH = 110;
var rectC = 'red';
function clear()
{
context.clearRect(0,0,canvas.width, canvas.height);
}
function drawRect(rectX,rectY,rectW,rectH,rectC)
{
context.fillStyle = rectC;
context.fillRect(rectX,rectY,rectW,rectH);
}
function drawCircle(circleX,circleY,circleR,circleC)
{
context.fillStyle = circleC;
context.beginPath();
context.arc(circleX,circleY,circleR,0,2 * Math.PI);
context.fillStyle = 'orange';
context.fill();
}
function update()
{
if (circleY > rectX && circleX < rectX + rectW &&
circleY > rectY && circleY < rectY + rectH){
circleSpeedX = circleSpeedY = 0;
rectC = 'GREEN';
}
else {
circleX += circleSpeedX;
circleY += circleSpeedY;
}
}
function draw()
{
clear();
drawRect(0,0,canvas.width,canvas.height,'black');
drawRect(rectX,rectY,rectW,rectH,rectC);
drawCircle(circleX,circleY,circleR,circleC);
}
function loop()
{
update();
draw();
setTimeout(loop, 30);
}
loop();