【问题标题】:XNA Sprite only Disappears when player intersectsXNA Sprite 仅在玩家相交时消失
【发布时间】:2014-09-03 22:03:13
【问题描述】:

我正在制作一个玩家将四处收集奇异果的游戏。当玩家触摸猕猴桃时,我希望猕猴桃精灵永久消失。到目前为止,我只能在玩家触摸猕猴桃精灵时让它们消失,而当玩家离开猕猴桃矩形时,猕猴桃精灵会重新出现。

这是我在 Kiwi 类中创建的 intersect 函数:

public void Intersect(Rectangle playerRect, SpriteBatch spriteBatch)
    {
        foreach (Rectangle kiwiRect in kiwiRectangle)
        {
            if (!kiwiRect.Intersects(playerRect))
            {
                isCollected = false;
            }
            else
                isCollected = true;

            if (!isCollected)
            {
                spriteBatch.Draw(kiwiTexture, kiwiRect, Color.White);
            }
        }
    }

然后我把这个函数放在游戏主类的Draw函数中。

    protected override void Draw(GameTime gameTime)
    {

         GraphicsDevice.Clear(Color.CornflowerBlue);
         spriteBatch.Begin();

         if (gameState == GameState.Playing)
         {


             GraphicsDevice.Clear(Color.Green);




             kiwiClass.Intersect(Sprite.spriteDestinationRectangle, spriteBatch);


             Sprite.Draw(spriteBatch);


         }



         spriteBatch.End();


         base.Draw(gameTime);
      }

【问题讨论】:

  • 嗯,您似乎没有在每个游戏对象上使用可覆盖的 Draw 方法。你能准确地展示这个 intersect 方法的去向吗?你的奇异果是 DrawableGameComponents 吗?或者他们只是在那个班级某个地方的列表中?

标签: c# xna sprite collision


【解决方案1】:

您应该只检查是否有交叉路口,直到有一个交叉路口。你永远不想做isCollected = false,否则奇异果会重新出现。

您的Intersect() 方法应如下所示:

public void Intersect(Rectangle rectangle, SpriteBatch spriteBatch)
{
    foreach (Rectangle kiwiRect in kiwiRectangle)
    {
        if (!isCollected)
        {
            if (kiwiRect.Intersects(playerRect))
            {
                isCollected = true;
            }
        }

        if (!isCollected)
        {
            spriteBatch.Draw(kiwiTexture, kiwiRect, Color.White);
        }
    }
}

编辑:实际上,您需要单独跟踪每个奇异果的收集状态。您可以将isCollected 改为列表:

List<Rectangle> collectedKiwis = new List<Rectangle>();

然后把Intersect()方法改成这样:

public void Intersect(Rectangle rectangle, SpriteBatch spriteBatch)
{
    foreach (Rectangle kiwiRect in kiwiRectangle.Except(collectedKiwis))
    {
        if (kiwiRect.Intersects(playerRect))
        {
            collectedKiwis.Add(kiwiRect);
        }
        else
        {
            spriteBatch.Draw(kiwiTexture, kiwiRect, Color.White);
        }
    }
}

【讨论】:

  • 你的方法让它们一下子消失了,然后就再也没有出现了
  • @user2681474 听起来你没有摆脱 !在kiwiRect.Intersects(...) 之前。只需照原样复制并粘贴我的代码即可。
  • 不,我做到了。我完全复制了你写的内容。
猜你喜欢
  • 1970-01-01
  • 2020-03-29
  • 2013-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多