三种状态:正常,跳跃,连按两次跳跃
左右键移动,空格键跳跃。跳跃过程中可以按左右键。
状态机编程:跳跃过程中,可以再按一次“跳”。第三次按“跳”,不起作用。
截图:
按键消息入口
//方向键功能函数。 按键按下,触发事件
msgmap=new Map();
msgmap.set(37, 'l'); // leftkey 37
msgmap.set(39,'r');
msgmap.set(32,'j');
document.onkeydown =function(e){
console.log( e.keyCode );
ch=msgmap.get(e.keyCode );
//按键码转换为对应的消息字符,如果为空,则返回
if(!ch )
return;
msg_resolution_state(ch);
gameupdate();
}
按键处理函数:
function msg_resolution_state(ch)
{
switch(state){
case 0: //
state0key(ch);
break;
case 2: //
state2key(ch);
break;
case 3: //
state3key(ch);
break;
default:
break;
}
}
三种状态,各自的按键处理函数
function state0key(ch)
{
switch(ch){
case 'l': //
direction=-1;
x+=direction *10; // 系数 1 right; -1,left
break;
case 'r': //
direction=1;
x+=direction *10; // 系数 1 right; -1,left
break;
case 'j':
state=2; //状态改变
speed_y=-15;
jump_cnt=1; //初始化
break;
case 's':
break;
default:
break;
}
}
function state2key(ch)
{
switch(ch){
case 'l':
case 'r': //
state0key(ch);
break;
case 'j': //已经跳了一次
state=3; //状态改变
speed_y=-15;
jump_cnt=1; //初始化
break;
default:
break;
}
}
// 连跳两次
function state3key(ch)
{
switch(ch){
case 'l':
case 'r': //
state0key(ch);
break;
case 'j': //已经跳了两次,不再处理跳跃按键
default:
break;
}
}
计时器刷新每帧画面,每次修改当前的速度增量-15,-13,-11,...,画出抛物线:
function gameupdate()
{
cnt++; //计数器
if( state == 2 || state == 3)
{
x+= direction *10;
y+= speed_y;
console.log(" speed "+speed_y+" ,"+ y);
jump_cnt++;//
speed_y+=2;
}
//function
checkcollision();
paintback(0, 0, w,h);
paintfr(x, y);
}
落地的碰撞检测:
function checkcollision()
{
if( x<0)
{
x=0;direction=1;
}
if( x> w-40)
{
x=w-40;direction=-1;
}
if( y>= low_y)
{
y= low_y;
state=0;
}
}
源码地址: 状态编程game3.2.html
链接: https://pan.baidu.com/s/1kR-DYDkNRqCFU7MfVxYNmg 提取码: 8add
有限状态机用的很多,可以参考前面的教程。