一般来说,我们设计一个敌人可以发射子弹的流程为:创建一个敌人,在敌人身上创建一个子弹发射器spawn,然后有子弹发射器生成子弹并发射出去。你会想,为什么不直接让敌人对象发射子弹?其实是可以的。我这样设计其实是把spawn看做一把武器,谁都可以用,不仅是敌人A、B、C,玩家也可以用,其他NPC也可以用。还可以设计多种spawn随时切换“武器”。先看效果图。
先设计一个spawn类,因为spawn是个点,我继承于
importPhaserfrom"phaser";importBulletfrom'./';{constructor(scene,target){super(scene);=target;=scene;=0;=0;=0;=();('bulletspawn');}setPosition(x,y){=x;=y;();(0xff0000,1);(,,2);}update(){if(%10==0){constbullet=newBullet(,,,);(,200,);(bullet,{runChildUpdate:true,});}++;if()=0;}}说明:
target是目标对象,比如:玩家
再设计一个子弹类,直接继承
importPhaserfrom"phaser";{constructor(scene,target,x,y){super(scene,x,y,'particle');=scene;=target;=1;(0.5,0.5);(this);//必须(this);//必须(,this,(a,b)={();();});//(this);}update(){if(||||||){();}}}创建场景
import{Scene}from'phaser';importBulletSpawnfrom'../classes/';exportclassGameextsScene{constructor(){super('Game');}preload(){('assets');('panel');('particle');}create(){constplayer=(600,225,'panel');=()={('hurt');};constspawn=newBulletSpawn(this,player);(100,225);(spawn,{runChildUpdate:true});}}说明一下(spawn,{runChildUpdate:true});因为spawn有一个update方法,但创建对象以后它不会自动运行。方法一:把()放在场景的update里,方法二:用group激活它,方法三:用time去执行它。