cocos creator 小球随重力感应滚动
[toc]
参考
- https://github.com/andynicoo/Physical-Pinball 物理弹球
- https://forum.cocos.com/t/creator/39436/2
- https://docs.cocos.com/creator/manual/zh/scripting/player-controls.html 文档
重力加速度监听
cc.Class({
extends: cc.Component,
properties: {
speed: cc.v2(0,0)
},
// LIFE-CYCLE CALLBACKS:
onLoad() {
// open Accelerometer
cc.systemEvent.setAccelerometerEnabled(true);
cc.systemEvent.on(cc.SystemEvent.EventType.DEVICEMOTION, this.onDeviceMotionEvent, this);
},
onDeviceMotionEvent(event) {
//log event
//console.log("event,x,y",event.acc.x,event.acc.y)
this.speed.x = event.acc.x;
this.speed.y = event.acc.y;
},
update(dt) {
let rightBody = this.node.getComponent(cc.RigidBody)
rightBody.linearVelocity = cc.v2(rightBody.linearVelocity.x + dt * this.speed.x*100, rightBody.linearVelocity.y + dt * this.speed.y*1000)
//获取刚体速度
//console.log("after",rightBody.linearVelocity)
},
onDestroy() {
//remove listener
cc.systemEvent.off(cc.SystemEvent.EventType.DEVICEMOTION, this.onDeviceMotionEvent, this);
cc.systemEvent.setAccelerometerEnabled(false);
}
});
bug解决
1.小球会随意跑飞
解决方案:添加物理边框
image2.边框大小在手机适配上的问题.
参考:
动态设置画布大小等一系列方案最终因为设备兼容的问题被pass掉.
最优解决方案:尽量设置大的画布,通过widget组件对齐使边框对齐顶级组件canvans
网友评论