从0开始用CocosCreator开发飞机大战小游戏(三)

143 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第10天,点击查看活动详情

今天说下如何通过脚本控制游戏角色。

1.在script文件夹下新建一个play.ts脚本 image.png

2. 在play.ts脚本添加监听事件,这样就可以通过脚本对游戏角色进行控制了。

    curPos:Vec3=null;

    onLoad(){

        this.node.on(Node.EventType.TOUCH_MOVE,this.onTouchCallback,this)

    }

    onTouchCallback(event:EventTouch){

        let location:Vec2=event.getLocation() //得到手指鼠标位置,得到的是世界坐标         this.curPos=this.node.parent.getComponent(UITransform).convertToNodeSpaceAR(v3(location.x,location.y,0)) //play的当前位置设置为手指鼠标的位置,并转化为局部坐标。

        this.node.setPosition(this.curPos)

    }

3. 还在加上取消监听

    onDisable(){

        this.node.on(Node.EventType.TOUCH_MOVE,this.onTouchCallback,this) //取消监听

    }

  4. 回到menu场景,新建一个空节点,并且命名为PersistNode,作为一个常驻节点 image.png

5.在script文件夹下新建一个脚本,并且命名为persistNode image.png

  6.将persistNode设置为常驻节点

    onLoad(){

        game.addPersistRootNode(this.node)

    }

7. 将脚本persistNode.ts挂载到persistNode上。 image.png

8. 新建一个脚本文件并且命名为gameFactory,把装饰器@ccclass('gameFactory'),继承等去掉。 image.png

代码如下

import { _decorator, Component, Node } from 'cc';

const { ccclass, property } = _decorator;

export class gameFactory  {

}

  9.完善gameFactory脚本。代码如下

import { _decorator, Component, Node, NodePool, find } from 'cc';

const { ccclass, property } = _decorator;

export class gameFactory  {

    productPool:NodePool=null;

    persistNode:Node=null;

    public constructor(){

        this.productPool=new NodePool() //建立节点池

        this.persistNode=find("persistNode")

    }

      public createProduct(productType:string):Node{

        return null;

    }

      public recycleProduct(product:Node){

        this.productPool.put(product)

    }  

}

  10. 在script文件夹下创建一个脚本,并且命名为playerBulletFactory。用作玩家子弹工厂。 image.png

11. 同样把装饰器@ccclass(playerBulletFactory)。并且继承gameFactory

import { _decorator, Component, Node } from 'cc';

import { gameFactory } from './gameFactory'

const { ccclass, property } = _decorator;

export class playBulltFactory extends gameFactory {

12.制作子弹预制体

(1)在assets文件夹下新建文件夹prefab用来存放预制体。 image.png  

(2)新建一个一个Sprite(精灵),并且命名为playerBullet image.png

(3)playerBullet关联对应的子弹图片资源。 image.png

(4) 在script下新建一个脚本,并且命名为playerBullet image.png

(5) 将脚本playerBullet.ts挂载到playerBullet节点上 image.png   (6)将playerBullet节点拖动到prefab文件夹上,并且将playerBullet节点删除。这样子弹的预制体就制作完了。

image.png

今天就到这里了,主要说了子弹预制体的制作。下一次再完善。可能写的过程中还有很多不好的地方,希望大家能指出来,在此,谢谢大家