CocosCreator物理引擎Demo源码分析(2)-tiled
生活随笔
收集整理的這篇文章主要介紹了
CocosCreator物理引擎Demo源码分析(2)-tiled
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
tiled示例展示了如何控制人物在地圖上左右和向上跳躍。
技術點
1、地圖由若干個剛體組成,攝像機跟隨人物高度位置做縮放。
2、通過施加沖量到剛體,快速改變剛體的線性速度。
3、通過改變剛體的線性速度來控制剛體左右運動。
源碼分析
hero-control.js
該源文件功能是通過鍵盤的方向鍵來控制人物的左右和向上跳躍。核心函數是設置 linearVelocity 值。
const MOVE_LEFT = 1; // 向左移動標志位 const MOVE_RIGHT = 2; // 向右移動標志位cc.macro.ENABLE_TILEDMAP_CULLING = false;cc.Class({extends: cc.Component,properties: {maxSpeed: 500, // 線性速度最大值jumps: 2,acceleration: 1500, // 每秒移動最大線性速度jumpSpeed: 200, // 跳起高度drag: 600 // 慣性速度},// LIFE-CYCLE CALLBACKS:onLoad () {// 注冊鍵盤按下和釋放事件的回調cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp, this);this.moveFlags = 0;this._up = false;},start () {// start 在 onLoad 之后,此時RigidBody組件已經被加載進來this.body = this.getComponent(cc.RigidBody);},onKeyDown(event) {switch(event.keyCode) {case cc.KEY.a:case cc.KEY.left:this.moveFlags |= MOVE_LEFT; // 添加向左移動的標志位break;case cc.KEY.d:case cc.KEY.right:this.moveFlags |= MOVE_RIGHT; // 添加向右移動的標志位break;case cc.KEY.up:if (!this._upPressed) {this._up = true; // 添加向上跳起的標志位}this._upPressed = true;break;}},onKeyUp (event) {switch(event.keyCode) {case cc.KEY.a:case cc.KEY.left:this.moveFlags &= ~MOVE_LEFT; // 清除向左移動標志break;case cc.KEY.d:case cc.KEY.right:this.moveFlags &= ~MOVE_RIGHT; // 清除向右移動標志break;case cc.KEY.up:this._upPressed = false;break;}},updateMotorSpeed(dt) {// 判斷this.body是否可用if (!this.body) {return;}var speed = this.body.linearVelocity;if (this.moveFlags === MOVE_LEFT) {// 如果目標當前是向右的,則做水平翻轉if (this.node.scaleX > 0) {this.node.scaleX *= -1;}speed.x -= this.acceleration * dt;if (speed.x < -this.maxSpeed) {speed.x = -this.maxSpeed;}} else if (this.moveFlags === MOVE_RIGHT) {// 如果目標當前是向左的,則做水平翻轉if (this.node.scaleX < 0) {this.node.scaleX *= -1;}speed.x += this.acceleration * dt;if (speed.x > this.maxSpeed) {speed.x = this.maxSpeed;}} else {if (speed.x != 0) {var d = this.drag * dt;if (Math.abs(speed.x) <= d) {speed.x = 0;} else {speed.x -= speed.x > 0 ? d : -d;}}}if (Math.abs(speed.y) < 1) {this.jumps = 2;}if (this.jumps > 0 && this._up) {speed.y = this.jumpSpeed; // 向上跳起this.jumps--;}this._up = false;// 通過改變剛體的線性速度來控制剛體的位置this.body.linearVelocity = speed;},update (dt) {this.updateMotorSpeed(dt);}, });impulse.js
該源文件功能是實現類似于彈簧式跳板,使人物急速上跳。核心函數是 applyLinearImpulse。
cc.Class({extends: cc.Component,properties: {impulse: cc.v2(0, 1000)},onBeginContact: function(contact, selfCollider, otherCollider) {// 獲取世界坐標系下的信息let manifold = contact.getWorldManifold();if (manifold.normal.y < 1) return;let body = otherCollider.body;body.linearVelocity = cc.v2();// 施加沖量到剛體上的中心點,改變剛體的線性速度body.applyLinearImpulse(this.impulse, body.getWorldCenter(), true);},// LIFE-CYCLE CALLBACKS:// onLoad () {},start () {},// update (dt) {}, });總結
以上是生活随笔為你收集整理的CocosCreator物理引擎Demo源码分析(2)-tiled的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: html定位fix,html 定位fix
- 下一篇: PHP怎么做一个加法口诀,神奇的手指速算