COCOS:(飞机大战11)主机注册碰撞事件,主机发生碰撞,闪烁,坠落销毁

前几节Player.ts中已经编写的触摸,子弹单双发的逻辑,
这节记录受伤闪烁,和结束坠机的代码。

	 /**
     * collider:Collider2D  注册碰撞事件
     * hp                   主机生命值
     * anim                 主机发生碰撞播放动画
     * animHit              受伤闪烁动画
     * animDown             坠机爆炸动画
     * secureTime           碰撞后的无敌时间
     * secureTimer          碰撞发生计时器
     * isSecure             是否处于安全时间
     */
    collider:Collider2D = null;
    @property
    hp:number = 3
    @property(Animation)
    anim:Animation = null;
    @property(String)
    animHit:string = '';
    @property(String)
    animDown:string = '';
    @property
    secureTime:number = 3;
    secureTimer:number = 0;
    isSecure:boolean = false;
	
    protected onLoad(): void {
        // 注册单个碰撞体的回调函数
        this.collider = this.getComponent(Collider2D);
        if (this.collider) {
            this.collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
        }
    }

    protected onDestroy(): void {
    	// 注销
        if (this.collider) {
            this.collider.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
        }
    }

    onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null){
        /**
         * 判断是否处于安全时间内
         * 发生碰撞后,安全状态改为true
         * 安全计时器归0
         * 生命值-=1
         * 如果生命值>0 播放闪烁动画
         * 否则播放坠机动画
         * 如果没有生命值了,就结束监听
         */
        if(this.isSecure) return;
        this.isSecure = true;
        this.secureTimer = 0;

        this.hp -= 1;
        if(this.hp>0){
            this.anim.play(this.animHit)
        }else{
            this.anim.play(this.animDown)
        }
        if(this.hp<=0){
            // 血量==0了,就需要禁用这个监听。否则会重复播放动画。
            if(this.collider){
                this.collider.enabled = false;
            }
            // 之前文章里有写,1单发,2双发,0不发射。死亡之后,停止发射子弹
            this.sendType = 0; // 不发射子弹
        }
    }
    
    protected update(dt: number): void {
    	/**
         * 如果处于安全状态
         * 计时器+=dt
         * 如果计时器时间>安全时间
         * 安全状态更改为false
         */
        if(this.isSecure){
            this.secureTimer+= dt
            if(this.secureTimer>this.secureTime){
                this.isSecure = false;
            }
        }
    }

回到COCOS,加上动画Body,填写动画名称
在这里插入图片描述

到项目设置中,增加碰撞分组

敌机可以和主机发生碰撞
在这里插入图片描述
回到Player,勾选分组
在这里插入图片描述
注意看右侧Player的hp 血量变化
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值