gpt4 book ai didi

javascript - Html5/Javascript 游戏延迟

转载 作者:行者123 更新时间:2023-11-28 02:00:03 25 4
gpt4 key购买 nike

我正在开发一个基本的太空射击游戏,目前玩家只是一个圆圈。

同时在 Opera、Firefox 和 IE9 中玩游戏时,我的游戏卡顿了。

我已经尝试研究这个问题,但我不确定哪里出了问题。

我做错了什么吗?

有什么想法吗?

代码如下:

<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>Space Game Demo</title>
</head>
<body>
<section>
<div>
<canvas id="canvas" width="640" height="480">
Your browser does not support HTML5.
</canvas>
</div>
<script type="text/javascript">
//Start of script
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var x = 200;
var y = 200;
var thrust = 0.25;
var decay = 0.99;
var maxSpeed = 2;
var turnSpeed = 2;
var tempSpeed = 0;
var direction = 0;
var xSpeed = 0;
var ySpeed = 0;

function move() {
if (38 in keysDown) { // Player holding up
xSpeed += thrust * Math.sin(direction * (Math.PI / 180));
ySpeed += thrust * Math.cos(direction * (Math.PI / 180));
}
else {
xSpeed *= decay;
ySpeed *= decay;
}
if (37 in keysDown) { // Player holding left
direction += turnSpeed;
}
if (39 in keysDown) { // Player holding right
direction -= turnSpeed;
}
if (40 in keysDown) { // Player holding down
}

tempSpeed = Math.sqrt((xSpeed * xSpeed) + (ySpeed * ySpeed));
if(tempSpeed > maxSpeed) {
xSpeed *= maxSpeed / tempSpeed;
ySpeed *= maxSpeed / tempSpeed;
}

x += xSpeed;
y += ySpeed;
}

function degtorad(angle) {
return angle * (Math.PI/180);
}

function loop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);

ctx.fillStyle = "grey";
ctx.strokeStyle = "black";
ctx.beginPath();
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.stroke();

move();
ctx.strokeStyle = "red";
ctx.beginPath();
ctx.arc(x,y,10,0,2*Math.PI);
ctx.stroke();
}

setInterval(loop, 2);
var keysDown = {};

addEventListener("keydown", function (e) {
keysDown[e.keyCode] = true;
}, false);

addEventListener("keyup", function (e) {
delete keysDown[e.keyCode];
}, false);

</script>
</section>
</body>
</html>

最佳答案

使用 window.requestAnimationFrame ,这就是它的意思。现在,您正在尝试以每两毫秒 1 步的速度运行游戏 - 即大约 500 FPS。

// target the user's browser.
(function() {
var requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;

window.requestAnimationFrame = requestAnimationFrame;
})();

function loop() {
// game loop logic here...
}

requestAnimationFrame(loop);

关于javascript - Html5/Javascript 游戏延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14492913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com