AS3角色通过平台,碰撞不能正常工作

时间:2014-12-18 19:08:21

标签: actionscript-3 collision-detection flashdevelop gravity

我正在制作2D平台游戏。我遇到了碰撞问题。当我的角色击中站在平台顶部时,它将在那里停留2.5秒,然后通过所有其他平台落到地面。我认为必须对我的引力函数和碰撞功能做一些不能正常工作的事情。我真的无法想出任何帮助将不胜感激。

this = fireboy1

这是我的角色类的重力代码:

public var gravity:int = 0;
public var floor:int = 461;

public function adjust():void
    {
        //applying gravity
        this.y += gravity;
        if(this.y + this.height <floor)
            gravity++;
        else
        {
            gravity = 0;
            this.y = floor - this.height;
        }

以下是来自主类的碰撞代码:

//collision detection of platform1
    public function platform1Collision():void
    {
        if(fireboy1.hitTestObject(Platform1))
        {
            if(fireboy1.y > Platform1.y)
            {
                fireboy1.y = Platform1.y + Platform1.height;
            }
            else
            {
                fireboy1.y = Platform1.y - fireboy1.height;
            }
        }

1 个答案:

答案 0 :(得分:0)

您的问题很可能是y位置每帧递增(无论是否有任何碰撞)

更好的方法是创建一个游戏循环/输入框架处理程序,而不是为玩家设置一个,每个平台一个等等。您还有一些不正确的数学计算玩家相对于平台和楼层的位置

public var gravity:int = 0;
public var floor:int = 461;

//add this in your constructor or init of the class
this.addEventListener(Event.ENTER_FRAME, gameLoop);

function gameLoop(e:Event):void {

    //start with all your platform collisions
    if(fireboy1.hitTestObject(Platform1))
    {
        if(jumping){ //some flag that indicates the player is jumping at the moment
           //place fireboy right under the platform
           fireboy1.y = Platform1.y + Platform1.height;
        }else{
           //place fireboy on the platform perfectly
           fireboy1.y = (Platform1.y + Platform1.height) - fireboy1.height; //changed your math here
            return; //there's no use checking any other platforms or doing the gravity increment, since the player is already on a platform, so exit this method now.
        }
    }

    //any other platform checks (should be done in a loop for sanity)

    //if we made it this far (no returns), then do the gravity adjustments
    fireboy1.y += gravity;
    if(fireboy1.y - fireboy1.height < floor){  //changed your math here
        gravity++;
    } else
    {
        gravity = 0;
        fireboy1.y = floor - fireboy1.height;
    }
}