【发布时间】:2021-07-24 08:54:13
【问题描述】:
我正在尝试用 Javascript 制作一个蛇游戏,这个数学 *if(secondsSinceLastRender
- 让我有点困惑,我不太明白它的作用...谁能解释一下?非常感谢!
这是我的 js,实际上是:
let lastRenderTime = 0
const SNAKE_SPEED = 2
function main(currentTime) {
const secondsSinceLastRender = (currentTime - lastRenderTime) / 1000
window.requestAnimationFrame(main)
if(secondsSinceLastRender < 1 / SNAKE_SPEED) return
lastRenderTime = currentTime
console.log(secondsSinceLastRender)
}
window.requestAnimationFrame(main)
这是我的html和css:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Snake</title>
<style>
body {
height: 100vh;
width: 100vw;
display: flex;
justify-content: center;
align-items: center;
margin: 0;
background-color: black;
}
#game-board {
background-color: #CCC;
width: 100vmin;
height: 100vmin;
display: grid;
grid-template-rows: repeat(21, 1fr);
grid-template-columns: repeat(21, 1fr);
}
#snake {
background-color: hsl(200, 100%, 50%);
border: .25vmin solid black;
}
#food {
background-color: hsl(50, 100%, 50%);
border: .25vmin solid black;
}
</style>
</head>
<body>
<div id="game-board"></div>
<script src="game.js" type="module"></script>
</body>
</html>
【问题讨论】:
标签: javascript render requestanimationframe