Cocos Creator之角色组合按键技能
2019-04-05 本文已影响271人
喜欢桃子的阿狸
想必大家都玩过街机游戏,例如红白机的街霸,拳皇,里面角色的技能是通过组合按键触发的,废话不多说,上测试图。
rpg.gif
代码
const {ccclass, property} = cc._decorator;
@ccclass
export default class player extends cc.Component {
//自定义方向键和攻击键
public KEY_UP:number = 0;
public KEY_DOWN:number = 1;
public KEY_LEFT:number = 2;
public KEY_RIGHT:number = 3;
public KEY_ATTACK:number = 4;
//技能列表中技能的数量
public SKILLLIST_SIZE:number = 1;
//每组组合技能的按键数量
public SKILL_KEYCOUNT = 3;
//技能列表->二维数组
private SkillList:Array<any> = [[this.KEY_DOWN,this.KEY_UP,this.KEY_ATTACK]];
//记录当前按下的按键的值
private currentKeyCode:number = 0;
//玩家输入的按键组合
private inputKeys:Array<any> = [];
//是否开始计时
private startFrame:boolean = false;
//限制输入组合按键的时间(计时器)
private timer:number = 5;
//记录开启监听到现在的时间
private time:number = 0;
//是否触发技能成功
private isSuccess:boolean = false;
onLoad () {
cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN,this.OnKeyDown,this);
}
start () {
}
update (dt) {
if (this.startFrame) {
//计时器++
this.time += dt;
if (this.time >= this.timer) {
//计时器超时
if (!this.isSuccess) {
this.Reset();
}
}
}
}
//按下按键
OnKeyDown(event){
console.log("按下的按键的keycode",event.keyCode);
switch (event.keyCode) {
case cc.macro.KEY.w:
this.currentKeyCode = this.KEY_UP;
break;
case cc.macro.KEY.s:
this.currentKeyCode = this.KEY_DOWN;
break;
case cc.macro.KEY.a:
this.currentKeyCode = this.KEY_LEFT;
break;
case cc.macro.KEY.d:
this.currentKeyCode = this.KEY_RIGHT;
break;
case cc.macro.KEY.j:
this.currentKeyCode = this.KEY_ATTACK;
break;
}
if (this.isSuccess) {
console.log("Reset");
this.isSuccess = false;
this.Reset();
}
if (!this.startFrame) {
//启动计时器
this.startFrame = true;
}
//将按键值添加到输入按键列表
this.inputKeys.push(this.currentKeyCode);
//遍历
let size = this.inputKeys.length;
if (size<this.SKILL_KEYCOUNT) { //按键数不够
}else{ //如果玩家按键数不小于设定键,取后5位
console.log("未移除前的元素",this.inputKeys);
for (let k = 0; k < size - this.SKILL_KEYCOUNT; k++) {
this.inputKeys.splice(0,1);
}
console.log("移除后的元素",this.inputKeys);
for (let i = 0; i < this.SKILLLIST_SIZE; i++) {
let successCount = 0;
for (let j = 0; j < this.SKILL_KEYCOUNT; j++) {
let temp = this.inputKeys[j];
if (temp == this.SkillList[i][j]) {
successCount ++;
}
if (successCount == this.SKILL_KEYCOUNT) {
console.log("isSuccess");
this.isSuccess = true;
//播放组合技能动画
break;
}
}
}
}
}
//重置
Reset(){
this.time = 0;
this.startFrame = false;
this.inputKeys = [];
}
}