【问题标题】:AS3 character falls through platforms, collisions not working properlyAS3 角色跌落平台,碰撞无法正常工作
【发布时间】:2014-12-18 19:08:21
【问题描述】:

我正在创建 2D 平台游戏。我的碰撞有问题。当我的角色命中站在平台顶部时,它将在那里停留 2.5 秒,然后穿过所有其他平台落到一楼。我认为这与我的重力功能和碰撞功能无法正常协同工作有关。我真的想不出任何帮助将不胜感激。

这 = 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;
            }
        }

【问题讨论】:

  • 尝试做:if((this.y + this.height)
  • 根本没有改变任何东西:(
  • 只是一个切线,但为此使用物理框架要容易得多。像 box2d 等。adjust()platform1Collision() 是否每帧都运行?理想情况下,它们应该具有相同的功能,如果发生碰撞,您不应该运行重力 (this.y += gravity)。更新您的问题以包含您的代码范围(例如,第一个块中的 this 是什么,以及它与第二个代码块有何关系)
  • firebox1 是否有左上角的注册点 (0,0)?如果是这样,检查if(fireboy.y &gt; Platform1.y) 似乎很奇怪,因为这意味着播放器的顶部必须超过平台的顶部。
  • 啊,好吧,这仍然不能阻止我的播放器在 2 秒后从平台上掉下来的问题

标签: actionscript-3 collision-detection flashdevelop gravity


【解决方案1】:

您的问题可能是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;
    }
}

【讨论】:

  • 这行得通,但是当 fireboy1 从下方撞到平台时,它会跳到平台顶部
  • 我明白了。您可以做以前的事情(使用位置来确定平台是在玩家上方还是下方),或者更好的方法是跟踪玩家的方向(他们是向上还是向下移动)并基于放置那个。
猜你喜欢
  • 2016-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-25
相关资源
最近更新 更多