我正在尝试制作一个游戏,你可以用箭头键控制一个盒子,但我卡住了。我以前使用过此代码并且它有效,但现在我发现了一个错误,我不知道如何修复它。
当这段代码有效时,玩家会玩得很多,我想做一个流畅的角色运动,我该怎么做?
如果有人能够解决这两个问题,我将非常感激
我到目前为止的代码是
var canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
var farge = ["blue", "darkorchid", "yellowgreen", "violet", "peru", "darkorange", "lightskyblue"];
var tileldig = Math.floor((Math.random() * 300) + 1);
var kuler = [
{r: 10, x: canvas.width/2, y: canvas.height-100, f: "red"},
//{r: 50, x: tileldig, y: 50, vx:0 , vy: 3, f: "green"},
]
var fiender = [
{r: 5, x: tileldig, y: 50, vx:0 , vy: 3, },
]
function bounceCircle () {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < kuler.length; i++) {
kuler[i].x += 0;
kuler[i].y += 0;
ctx.fillStyle = kuler[i].f;
ctx.beginPath();
ctx.arc(kuler[i].x, kuler[i].y, kuler[i].r, 2*Math.PI, 0);
ctx.closePath();
ctx.fill();
function tast (e) {
if (e.keyCode == 37) {
kuler[i].x -= 10;
};
if (e.keyCode == 39) {
kuler[i].x += 10;
};
if (e.keyCode == 38) {
kuler[i].y -= 10;
};
if (e.keyCode == 40) {
kuler[i].y += 10;
};
}
document.onkeydown = tast;
};
for (var i = 0; i < fiender.length; i++) {
ctx.fillStyle = "blue";
ctx.beginPath();
ctx.arc(fiender[i].x, fiender[i].y, fiender[i].r, 2*Math.PI, 0);
ctx.closePath();
ctx.fill();
fiender[i].y += fiender[i].vy;
if (fiender.y >= canvas.height) {
circles.splice(i,1)
};
}
requestAnimationFrame(bounceCircle);
}
setInterval(function(){
fiender.push({r: 5, x: Math.floor((Math.random() * 300) + 1), y: 0, vx:0 , vy: 3, f: "green"});
}, 800);
bounceCircle();
查看我到目前为止的演示点击链接DEMO
感谢
答案 0 :(得分:0)
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
farge = ["blue", "darkorchid", "yellowgreen", "violet", "peru", "darkorange",
"lightskyblue"],
tileldig = Math.floor((Math.random() * 300) + 1);
var kuler = [
{r: 10, x: canvas.width/2, y: canvas.height-100, f: "red"},
//{r: 50, x: tileldig, y: 50, vx:0 , vy: 3, f: "green"},
];
var fiender = [
{r: 5, x: tileldig, y: 50, vx:0 , vy: 3, },
];
document.onkeydown = function tast (e) {
switch (e.keyCode) {
case 37:
kuler[0].x -= 10;
break;
case 39:
kuler[0].x += 10;
break;
case 38:
kuler[0].y -= 10;
break;
case 40:
kuler[0].y += 10;
break;
}
};
function bounceCircle () {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < kuler.length; i++) {
kuler[i].x += 0;
kuler[i].y += 0;
ctx.fillStyle = kuler[i].f;
ctx.beginPath();
ctx.arc(kuler[i].x, kuler[i].y, kuler[i].r, 2*Math.PI, 0);
ctx.closePath();
ctx.fill();
}
for (var i = 0; i < fiender.length; i++) {
ctx.fillStyle = "blue";
ctx.beginPath();
ctx.arc(fiender[i].x, fiender[i].y, fiender[i].r, 2*Math.PI, 0);
ctx.closePath();
ctx.fill();
fiender[i].y += fiender[i].vy;
if (fiender.y >= canvas.height) {
circles.splice(i,1)
}
}
requestAnimationFrame(bounceCircle);
}
setInterval(function(){
fiender.push({r: 5, x: Math.floor((Math.random() * 300) + 1), y: 0, vx:0 ,
vy: 3, f: "green"});
}, 800);
bounceCircle();
这有效(fiddle),虽然它不再循环通过多个“kuler”。我不清楚为什么你需要不止一个给出这个例子,但这应该让你朝着正确的方向前进。