cocos creator第一个小游戏:子弹发射 | 血影

制作游戏代码game.js,获取点击事件,发射子弹

cc.Class({
    extends: cc.Component,
    properties: {       
        player: { type:cc.Node, default:null},
        ground: {type:cc.Node,default:null},
        aa: { type:cc.Prefab, default:null},
        bb:{type:cc.Prefab, default:null},
        score:{ type:cc.Label, default:null},
        bullet_Num: 0,
        bullet_Speed : 0,
    },
    mouse (){
        this.node.on(cc.Node.EventType.TOUCH_START,function(event){
            var touch =event.getTouches()[0];
            var position = touch.getLocation();
            var localPosition = this.node.convertToNodeSpaceAR(position);
            this.shutboot(localPosition);
        },
        this
    );
    },
    newgoal(){
        if(this.gg!=null){
            this.gg.destroy();
        }
        var gg=cc.instantiate(this.bb);
        this.node.addChild(gg);
        gg.position=this.randomPosition();
        this.gg=gg;
    },
    randomPosition() {
        var x = this.node.width/2 * cc.randomMinus1To1();
        var y = 320* cc.random0To1();
        return cc.p(x, y);
    },
    shutboot (eposition){
        if(0 < this.bullet_Num ){
            var sb = cc.instantiate(this.aa);
            this.node.addChild(sb);
            sb.position = this.player.position;
            let shutbootg = sb.getComponent("rigidBody");
            eposition=cc.pNormalize(cc.pSub(eposition,sb.position));
            sb.getComponent(cc.RigidBody).linearVelocity = cc.pMult(eposition,this.bullet_Speed);
            this.bullet_Num --;            
        }
    },
    scoreAdd(){
        this.count++;
        this.score.string="Score : "+this.count;
    },
    onLoad () {
        cc.director.getPhysicsManager().enabled=true;
        cc.director.getPhysicsManager().debugDrawFlags = cc.PhysicsManager.DrawBits.e_aabbBit;
        this.mouse();
        this.count=0;
        this.gg=null;
        this.newgoal();
     },

});










制作发射的子弹创建,消失事件。

cc.Class({
    extends: cc.Component,
    properties: {
    },
    onBeginContact(contact,thisCollider,otherCollider){
        if(otherCollider.node.name=="goal"){
            otherCollider.node.parent.getComponent("game").newgoal();
            otherCollider.node.parent.getComponent("game").scoreAdd();
        }
      this.node.destroy(); 
      this.node.parent.getComponent("game").bullet_Num++;
    },
    onload(){
    },
    update(dt){
        // if(this.node.y>800){ 
        //     this.node.destroy();      
        //     this.node.parent.getComponent("game").bullet_Num--;  
        // }
    }
});

你可能感兴趣的:(cocos creator第一个小游戏:子弹发射 | 血影)