【问题标题】:xna: several sprites collision treatmentxna:几个精灵碰撞处理
【发布时间】:2014-03-19 00:12:45
【问题描述】:

我正在使用 xna 框架 (monogame) 创建一个小型教育游戏。

我在屏幕上有许多精灵使用 velocite 单独移动。我想添加碰撞处理,所以当 2 个或更多精灵相交时,它们会改变方向。但目前我还没有解决它!

这是每个精灵的更新方法:

 public void Update(GameTime gameTime)
    {
        if (CollisionDetected())
        {
            Xvelocity = -Xvelocity;
            Yvelocity = -Yvelocity;
        }
        position.X += Xvelocity;
        position.Y += Yvelocity;          
    }

 private bool CollisionDetected()
    {
        for (int i = 0; i < ListCount.Count(); i++)
        {
            if ((this.rectangle().Intersects(ListCount[i].rectangle()))
            {
                return true;
            }
        }
        return false;
    }

任何关于如何做到这一点的提示或想法都会很棒

【问题讨论】:

  • ListCount 是所有精灵的列表吗?
  • 是的,我从 spriteManager 类中恢复它是静态的。

标签: c# xna collision-detection monogame


【解决方案1】:

看起来你在碰撞中所做的一切都是正确的(假设ListCount 是所有精灵的列表);但是,我没有看到任何更新碰撞矩形的东西。您正在修改精灵的位置,而不是它们的碰撞矩形。我会尝试添加这个(假设位置是指左上角):

public void Update(GameTime gameTime)
{
    if (CollisionDetected())
    {
        Xvelocity = -Xvelocity;
        Yvelocity = -Yvelocity;
    }
    position.X += Xvelocity;
    position.Y += Yvelocity;     
    this.rectangle = new Rectangle(position.X, position.Y, rectangle.Width, rectangle.Height);     
}

这应该会导致矩形与精灵一起移动,然后碰撞应该起作用。

注意,如果位置是指精灵的中心,那么使用这个:

this.rectangle = new Rectangle(position.X - rectangle.Width / 2,
   position.Y - rectangle.Height / 2, rectangle.Width, rectangle.Height);   

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-04
    • 1970-01-01
    相关资源
    最近更新 更多