效果如下:(用上下左右控制走动,碰到墙会停下来,按住CTRL会跑。)
AS如下:
var walkspeed = 1.5;//走的速度
var runspeed = 3;//跑的速度
var numOfMask = 5;//Mask的数量
block_mc._visible = false;//挡着角色运动的MC看不见
for (i=numOfMask; i>0; i--) {
eval("mask" add i)._visible = false;//让所有MASK看不见
}
onEnterFrame = function () {
Key.isDown(Key.CONTROL) ? speed=runspeed : speed=walkspeed;//如果按下CTRL,就跑
if (Key.isDown(Key.LEFT)) {//如果按下左
Key.isDown(Key.UP) || Key.isDown(Key.DOWN) ? (character_mc._x -= 0.707*speed, xy=false) : (character_mc._x -= speed, xy=true);//同时又按下了上或者下,那就不要移动这么大.也就是说斜走的时候,角色在X轴或者Y轴上移动要小一点.下同
}
if (Key.isDown(Key.RIGHT)) {
Key.isDown(Key.UP) || Key.isDown(Key.DOWN) ? (character_mc._x += 0.707*speed, xy=false) : (character_mc._x += speed, xy=true);
}
if (Key.isDown(Key.UP)) {
Key.isDown(Key.LEFT) || Key.isDown(Key.RIGHT) ? (character_mc._y -= 0.707*speed, xy=false) : (character_mc._y -= speed, xy=true);
}
if (Key.isDown(Key.DOWN)) {
Key.isDown(Key.LEFT) || Key.isDown(Key.RIGHT) ? (character_mc._y += 0.707*speed, xy=false) : (character_mc._y += speed, xy=true);
}
for (i=numOfMask; i>0; i--) {
if (eval("mask" add i).hitTest(character_mc) && eval("mask" add i)._y>character_mc._y) {//如果角色和MASK相碰,而且MASK在角色下边的话,也就是说如果MASK应该挡着角色的话
bg_mc.setMask(eval("mask" add i));//那就用这个MASK挡着角色
break;//后边的就不用想了,跳出IF
}
}
shedowLx = character_mc._x-character_mc.shedow_mc._width/2;//得到角色影子最左边的X座标,后边做HITTEST时要用
shedowRx = character_mc._x+character_mc.shedow_mc._width/2;//影子最右边的X座标
shedowUy = character_mc._y-character_mc.shedow_mc._height/2;//影子最上边的Y座标
shedowDy = character_mc._y+character_mc.shedow_mc._height/2;//影子最下边的Y座标
shedowx = character_mc._x;//影子中心X座标
shedowy = character_mc._y;//影子中心Y座标
xy ? a=1 : a=0.8;//如果刚才是斜着走的话,反弹的速度A就是0.8,否则是1
block_mc.hitTest(shedowLx, shedowy, true) ? character_mc._x += a*speed : a=a;//如果影子的左边碰到不能走的地方,就向右弹出一个距离,距离的大小由上一句控制,下同
block_mc.hitTest(shedowRx, shedowy, true) ? character_mc._x -= a*speed : a=a;
block_mc.hitTest(shedowx, shedowUy, true) ? character_mc._y += a*speed : a=a;
block_mc.hitTest(shedowx, shedowDy, true) ? character_mc._y -= a*speed : a=a;
};