游戏在进行过程中,会涉及各种状态的切换,比如一个人有攻击,移动,站立三种状态,攻击可以和移动互相转换状态,移动和站立也可以互相转动状态,攻击和站立也可以互相转换动态,这就符合有限状态机的时候,当情况简单的时候,可以在一个类中进行这三种状态的转换,但是当情况复杂,那么可以每种状态一个类,再把拥有各种状态的类,也就是人这个对象,传到状态里,再进行操作。请看以下代码。
var Player = cc.Sprite.extend({
currentState:null,//当前状态
addDistance:0,
ctor:function(){
this._super();
this.actionArr = ["攻击1-斜方刺击","攻击2_直线刺击","横劈","攻击4_跃起砍击"];
this.armature = ccs.Armature.create("zhaoyun");
this.addChild(this.armature);
this.breathe();
},
//更新
update:function(enemyArr){
this.seekEnemy(enemyArr);
if(this.direction == 1){
this.x += 5;
}else if(this.direction == -1){
this.x -= 5;
}
},
//探索敌人
seekEnemy:function(enemyArr){
if(!enemyArr){
return;
}
for(var i in enemyArr){
var enemy = enemyArr[i];
if(Math.abs(this.x - enemy.x) <= 200){//如果自己的距离敌人足够近了
this.attack(enemy);
}
}
},
//攻击
attack:function(enemy){
if(this.isCanAttack()){
if(this.currentState == "run" || this.currentState == "breathe"){//简单状态机,从其他模式转化为攻击模式
this.currentState = "attack";
this.armature.getAnimation().play("攻击1-斜方刺击");
var func = function(armature, movementType){
if (movementType == ccs.MovementEventType.loopComplete && this.currentState == "attack") {
this.breathe();
enemy.hurt();
}
}
this.armature.getAnimation().setMovementEventCallFunc(func,this);
}
}
},
//是否可以攻击
isCanAttack:function(){
if(this.currentState == "run"){
return false;
}
return true;
},
//呼吸
breathe:function(){
if(!this.currentState || this.currentState == "run" || this.currentState == "attack"){//简单状态机,从其他模式转变为呼吸模式
this.currentState = "breathe";
//this.direction = 0;
this.armature.getAnimation().play("呼吸");//默认站着呼吸
}
},
//站立
stand:function(){
this.direction = 0;
this.breathe();
},
//跑步
run:function(){
if(this.currentState == "attack" || this.currentState == "breathe"){//简单状态机,从其他模式转变为跑步模式
this.currentState = "run";
this.armature.getAnimation().play("跑步_改");//默认站着呼吸
}
},
//向左移动
moveLeft:function(){
this.direction = -1;
this.run();
},
//向右移动
moveRight:function(){
this.direction = 1;
this.run();
}
})