问题
原因是想实现马里奥这样,平台跳跃游戏,当角色跳到平台上,可以跟随平台一起上下或者左右移动,在unity里面比较简单,直接设置角色的父节点是平台就可以了,但是cocos creator 就出现问题,这里提供解决方法。
关键点
移动平台,需要设置 RigidBody 为 kinematic,之后移动通过控制刚体的linearVelocity来处理
之后控制代码如下
const {
ccclass, property} = cc._decorator;
@ccclass
export default class PlatformMotion extends cc.Component {
@property speed:number = 10; // 移动的速度
@property distance = 200; // 移动的距离
@property leftright = true; // 左右移动还是上下移动
body: cc.RigidBody = null;
_movedDistance:number = 0.0;
_direction:number = 0;
_movedDiff:number = 0;
onLoad () {
this._movedDistance = this.distance / 2;
this._direction = 1;
this._movedDiff = 0;
}
start () {
this.body = this.getComponent(cc.RigidBody);
this.updateVelocity();
}
updateVelocity(){
var vspeed = this._direction * this.speed;
let v = cc.v2(0, vspeed)
if (this.leftright){
v = cc.v2(vspeed, 0)
}
this.body.linearVelocity = v;
}
update (dt) {
var d = this.speed * this._direction * dt;
this._movedDistance += Math.abs(d);
if (this._movedDistance > this.distance) {
// 切换方向
d = this.distance - this._movedDistance;
this._movedDistance = 0;
this._direction *= -1;
this.updateVelocity();
}
}
}
角色设置
角色的代码,我这里添加了一些动画的控制,整体代码如下
const {
ccclass, property} = cc._decorator;
@ccclass
export default class Player extends cc.Component {
@property(cc.Node) colliderTag:cc.Node = null; // 标记是否碰撞
@property(cc.Label) desc:cc.Label = null; // 用于显示各种说明文字的
@property(cc.Node)