当前位置:
首页 >
CocosCreator物理引擎Demo源码分析(2)-tiled
发布时间:2023/12/10
62
豆豆
生活随笔
收集整理的这篇文章主要介绍了
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
- 下一篇: flume简介(大数据技术)