cocos creator实现电梯,角色跟随平台上下左右移动

问题

原因是想实现马里奥这样,平台跳跃游戏,当角色跳到平台上,可以跟随平台一起上下或者左右移动,在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)
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值