const canvas = document.querySelector('#canvas')
const context = canvas.getContext('2d')
let rectX = 0 ;
let rectY = 0;
let secondsPassed = 0;
let timeStamp = 0
let oldTimeStamp = 0;
let movingSpeed = 50;
gameLoop()
function draw() {
context.fillStyle = 'red';
context.fillRect(rectX, rectY, 150, 100);
}
function gameLoop(timeStamp) {
// Calculate how much time has passed
secondsPassed = (timeStamp - oldTimeStamp) / 1000;
oldTimeStamp = timeStamp;
update(secondsPassed);
draw();
window.requestAnimationFrame(gameLoop);
}
function update(secondsPassed) {
rectX = (movingSpeed * secondsPassed);
rectY = (movingSpeed * secondsPassed);
}
rectX 和 rectY 最初有一個數字值,movingSpeed 也有一個數字值, secondsPassed 以及。我的問題是為什么函式“update”給變數 rectX 和 rectY NaN ?控制臺中沒有顯示錯誤。我嘗試記錄并使用 typeof 來檢查是否每個變數都有一個帶有型別編號的值,我注意到 rectX 曾經被認為是一個字串,我嘗試決議 rectX 的浮點數,但它仍然給了我 NaN。通常,我們使用 timeStamp 回傳一個可以幫助我們計算 fps 的值。在這種情況下,我使用 timeStamp 來查看在運行函式 gameLoop 之前已經過去了多少秒。我這樣做是因為決定游戲速度的不再是幀速率(和硬體),而是時間。
更新:感謝@epascarello、@James 和@Kaiido 解決了。有更新的代碼給你們:
const canvas = document.querySelector('#canvas')
const context = canvas.getContext('2d')
let rectX = 0;
let rectY = 0;
let secondsPassed = 0;
let oldTimeStamp = 0;
let timeStamp = 0
let movingSpeed = 50;
let timePassed = 0
function draw() {
context.fillStyle = 'red';
context.fillRect(rectX, rectY, 150, 100);
}
function gameLoop(timeStamp) {
// Calculate how much time has passed
secondsPassed = (timeStamp - oldTimeStamp) / 1000;
oldTimeStamp = timeStamp;
// Pass the time to the update
update(secondsPassed);
draw();
window.requestAnimationFrame(function(timeStamp){gameLoop(timeStamp)});
}
function update(secondsPassed) {
// Use time to calculate new position
rectX = (movingSpeed * secondsPassed);
rectY = (movingSpeed * secondsPassed);
}
window.requestAnimationFrame(function(timeStamp){gameLoop(timeStamp)});
uj5u.com熱心網友回復:
您的問題let rectX;在第 3 行創建了一個“未定義”
如果您使用rectX = 1js 嘗試添加 undefined 1 (自動從 undefined 轉換字串)
sting int = NaN
let rectX = 0;
let rectY = 0;
let speed = 1;
function update(seconds){
rectX = (speed * seconds);
rectY = (speed * seconds);
}
// test:
update(5);
console.log(rectX, rectY); // output is 5 5
uj5u.com熱心網友回復:
問題是當您最初呼叫它時,您沒有將 timeStamp 傳遞到 gameLoop 函式中。在 gameLoop 中,timeStamp未定義,這會破壞其他變數。
您可以在第一次呼叫時傳入當前時間戳。而不是
gameLoop()嘗試
gameLoop(Date.now().getTime())
uj5u.com熱心網友回復:
初始化變數 rectX 和 rectY 可能會有所幫助。
嘗試這個:
rectX = 0;
rectY = 0;
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/366659.html
標籤:javascript 动画片 帆布
上一篇:SwiftUI:顯示沒有影片的fullScreenCover
下一篇:滑動擴展影片旁邊的專案
