javascript
原生JS超级马里奥(第三天)
上一章主要是繪制馬里奧和繪制圖像代碼的部分重構
本章主要是用于時間控制,實現馬里奧每次彈跳的定點和彈跳起點一致,對源代碼拆分比較多,各位可以跟著原作者視頻一起敲
本章的提交ID:90dc4d0a02cc67339b120e55f29e46751e76e0c6、6773e3baedba43f22978e2d0a2a61f514fa524d1
github地址:ainuo5213的超級馬里奧
本節目錄
?本章效果
?
目錄說明:
????????mario.js:馬里奧實體工廠類文件,用于創建馬里奧,封裝馬里奧的繪制過程
????????Entity.js:馬里奧實體類,用于記錄實體的位置和速度等信息
? ? ? ? Velocity.js:用來記錄馬里奧橫向和縱向速度的實體
? ? ? ? Timer.js:繪制瑪麗奧,更新馬里奧位置的方法(原入口文件main方法中的update)封裝
入口文件改動
?入口文件改動:
? ? ? ? 1. 將原本加載馬里奧的方法移動到了mario.js
????????2. 將馬里奧位置改變的方法也內聚到了mario.js,并新增了橫向和縱向速度變量對象,實現對橫向速度和縱向速度的控制
Entity實體:
Entity實體主要用于對速度和位置的記錄對象,其實現交給馬里奧工廠函數
import { Velocity } from "./Velocity.js";export class Entity {constructor() {this.pos = new Velocity(0, 0);this.vel = new Velocity(0, 0);} }創建馬里奧工廠函數
創建馬里奧的工廠函數將原本loadMarioSprite方法內聚返回了馬里奧對象,并在馬里奧對象上面增加了兩個方法分別是drawMario(繪制馬里奧)和updateMario(更新馬里奧位置)的方法,其中updateMario方法將速度和時間進行累加操作,使馬里奧不再做勻速運動
import { Entity } from "./Entity.js" import { loadMarioSprite } from "./sprites.js";export function createMario() {return loadMarioSprite().then(marioSprite => {const mario = new Entity();mario.draw = function drawMario(context) {marioSprite.draw('mario', context, this.pos.x, this.pos.y);}mario.update = function updateMario(deltaTime) {this.pos.x += this.vel.x * deltaTime;this.pos.y += this.vel.y * deltaTime;}return mario;}) }馬里奧運動的時間控制
為實現馬里奧的每次跳躍的定點都保持在y軸方向一致,原作者這里使用累加法,當誤差大于閾值時,就減去閾值,相當于歸0
馬里奧入口中增加了update方法,用于updateProxy調用,來更新馬里奧位置。
export default class Timer {constructor(deltaTime = 1 / 60) {let accumulatedTime = 0;let lastTime = 0;this.updateProxy = time => {// 因為deltaTime是以秒為單位,所以這里運動的累加誤差時間需要除以1000accumulatedTime += (time - lastTime) / 1000;while (accumulatedTime > deltaTime) {this.update(deltaTime);accumulatedTime -= deltaTime}lastTime = time;this.enqueue();}}enqueue = () => {requestAnimationFrame(this.updateProxy);}start = () => {this.enqueue();} }總結
以上是生活随笔為你收集整理的原生JS超级马里奥(第三天)的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 为什么使用reStructuredTex
- 下一篇: DWG TrueView 2013 –
