我正在AS3中开展一个简单的游戏,玩家应该可以跳到一个盒子上。 如何检测播放器是否落在盒子上并且没有碰到它?
AS3让玩家跳跃:
var grav:Number = 10;
var jumping:Boolean = false;
var jumpPow:Number = 0;
stage.addEventListener(KeyboardEvent.KEY_DOWN, onDown);
stage.addEventListener(Event.ENTER_FRAME, update);
function onDown(evt:KeyboardEvent):void
{
if(evt.keyCode == Keyboard.UP)
{
//umbau das mehrfach tab bis höhe erreicht?
if(jumping != true)
{
jumpPow = -10;
jumping = true;
}
}
}
function update(evt:Event):void
{
if(jumping)
{
player_mc.y += jumpPow;
jumpPow += grav;
if(player_mc.y >= stage.stageHeight)
{
jumping = false;
player_mc.y = stage.stageHeight;
}
}
}
这就是游戏布局的样子:(灰色框从右向左移动,玩家的位置是固定的)
答案 0 :(得分:0)
您应该从一个简单的矩形碰撞函数开始:
/* Test collision between a rectangle and another rectangle. */
/* right() and bottom() return x+width and y+height of the parent rectangle. */
Rectangle.prototype.collideRectangle=function(rectangle_){
if (this.x>rectangle_.right()||this.y>rectangle_.bottom()||this.right()<rectangle_.x||this.bottom()<rectangle_.y){
return false;
}
return true;
}
如果您使用灰色矩形作为平台,您可以使用其当前和最后位置进行简单测试,以查看红色矩形是否落在灰色矩形上:
/* If true, the two rectangles are definitely colliding. */
if (red_rect.collideRectangle(gray_rect)){
/* Get the last position of the bottom of the red rectangle. */
var old_bottom=red_rect.bottom()-red_rect.velocity.y;
/* If the old bottom was above the gray rectangle on the last frame and is colliding in this frame, you know that the red rectangle is landing on the gray rectangle. */
if (old_bottom<gray_rect.y){
/* Place the red rectangle on top of the gray rectangle. */
red_rect.y=gray_rect.y-red_rect.height;
}
}
这假设您通过将velocity.y
的值添加到每个帧的y位置来移动红色矩形。另外,我使用的是JavaScript,但AS3和JavaScript并没有那么不同。
如果您需要的不仅仅是一个平台,而且想要完全碰撞,则应考虑红色矩形在灰色矩形上的穿透深度,并将它们分离在具有最小穿透深度的轴上。关于这个东西在网上有很多资源,特别是AS3有很多与游戏相关的教程,重点是自己做物理。一些非常好的碰撞方法是轴分离定理(SAT)和GJK(我不会尝试拼写GJK中的名字)。