Javascript 我的游戏循环加速,角色留下痕迹
守则:Javascript 我的游戏循环加速,角色留下痕迹,javascript,game-loop,Javascript,Game Loop,守则: // create stuff var ghObj = { x : 0, y : 0 } var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var ghost = new Image(); ghost.src = "ghost.png" //define variables var ghostMove = function () { ghObj.x+=(Math.
// create stuff
var ghObj = {
x : 0,
y : 0
}
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var ghost = new Image();
ghost.src = "ghost.png"
//define variables
var ghostMove = function () {
ghObj.x+=(Math.floor(Math.random() * 9 - 4))
console.log(ghObj.x)
ghObj.y+=(Math.floor(Math.random() * 9 - 4))
}
var ghostCheck = function () {
if (ghObj.x<0) {
ghObj.x=0
}
if (ghObj.x>390) {
ghObj.x=390
}
if (ghObj.y<0) {
ghObj.y=0
}
if (ghObj.y>390) {
ghObj.y=390
}
}
var drawIm = function (sprite, position) {
ctx.save();
ctx.translate(position.x, position.y);
ctx.drawImage(sprite, 0, 0, sprite.width, sprite.height, 0, 0, sprite.width, sprite.height);
ctx.restore();
};
// begin "game" when ghost is loaded
ghost.onload = function() {
mainLoop()
}
// main loop
function() {
ghostMove()
ghostCheck()
drawIm(ghost, ghObj)
setInterval(mainLoop, 1000)
}
//创建内容
var ghObj={
x:0,,
y:0
}
var canvas=document.getElementById(“canvas”);
var ctx=canvas.getContext(“2d”);
var ghost=新图像();
ghost.src=“ghost.png”
//定义变量
var ghostMove=函数(){
ghObj.x+=(Math.floor(Math.random()*9-4))
console.log(ghObj.x)
ghObj.y+=(Math.floor(Math.random()*9-4))
}
var ghostCheck=函数(){
如果(ghObj.x390){
ghObj.x=390
}
如果(ghObj.y390){
ghObj.y=390
}
}
var drawIm=函数(精灵,位置){
ctx.save();
平移(位置x,位置y);
ctx.drawImage(sprite,0,0,sprite.width,sprite.height,0,0,sprite.width,sprite.height);
ctx.restore();
};
//开始“游戏”时,鬼加载
ghost.onload=函数(){
mainLoop()
}
//主回路
函数(){
鬼魂行动
幻影检查()
drawIm(鬼,ghObj)
设置间隔(主回路,1000)
}
对不起,如果有点长
应该发生的是幽灵以稳定的速度在屏幕上随机移动。
相反,它的移动是随机的,但速度越来越快,到处都是自己的副本
还原功能不是每次都应该清除屏幕吗
我把游戏循环搞错了吗?
提前谢谢
function mainLoop(){
setInterval(mainLoop,100);
}
我认为错误是显而易见的。我建议改用setTimeout或requestAnimationFrame。。。这应该可以去除重复的部分我认为这是一个光学融合
…没有。使用clearRect我认为您应该重新阅读BASIC@darkrum因为?我早些时候试过setTimeout和clearRect,但肯定是把什么东西弄错了:(经验教训:每件事都试两次