2010-12-16 68 views
0

我目前工作的一个游戏,在此我们需要使用相结合的DrawUserIndexedPrimitives和正常spriteBatch.Draw。没有组合,因为我们同时使用它们,但我们首先必须使用spriteBatch绘制一些2d精灵,在此之后,我们禁用spriteBatch以启用basicEffect并绘制基元,最后再次启用spriteBatch。下面的代码显示了问题发生的代码部分。XNA 4.0 - 使用spriteBatch和basicEffect滞后

spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, null, cam.get_transformation(GraphicsDevice)); 
       levelController.Draw(spriteBatch); 


       if (gameReady) 
       { 
        foreach (GameObject.GameObject go in gameObjects) 
        { 
         go.Draw(spriteBatch); 
        } 
        spriteBatch.End(); 

        foreach (GameObject.GameObject go in gameObjects) 
        { 
         if (go is GameObject.Enemy.Enemy) 
         { 
          GameObject.Enemy.Enemy enemy = (GameObject.Enemy.Enemy)go; 

          basicEffect = new BasicEffect(graphics.GraphicsDevice); 
          basicEffect.VertexColorEnabled = true; 
          basicEffect.CurrentTechnique.Passes[0].Apply(); 

          GraphicsDevice.DrawUserIndexedPrimitives<VertexPositionColor>(PrimitiveType.TriangleList, enemy.GetCollisionTriangle.Triangle, 0, 3, enemy.GetCollisionTriangle.Indices, 0, 1); 
         } 
        } 
       } 

       spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, null, cam.get_transformation(GraphicsDevice)); 

如果下面的代码被引用,则滞后停止。

basicEffect = new BasicEffect(graphics.GraphicsDevice); 
         basicEffect.VertexColorEnabled = true; 
         basicEffect.CurrentTechnique.Passes[0].Apply(); 

         GraphicsDevice.DrawUserIndexedPrimitives<VertexPositionColor>(PrimitiveType.TriangleList, enemy.GetCollisionTriangle.Triangle, 0, 3, enemy.GetCollisionTriangle.Indices, 0, 1) 

难道真的是我们不能同时使用spriteBatch和basicEffect而没有游戏滞后很多?它已经在3台不同的电脑上测试过,从一台非常旧的笔记本电脑到一台全新的玩家电脑。 游戏无法播放,发生滞后。

回答

3

我认为你应该在其他地方创建basiceffect然后你的绘图程序。如果我猜对了,你会一直使用相同的basiceffect,所以把它变成官方的,因为每一帧的“新”(编辑:在每一个对象的foreach中)都会降低性能。

+0

谢谢,我想我们已经试过了,但我猜不是:) – Basic 2010-12-16 12:45:47

+1

+1:现在你提到它了,我再次查看代码,继续创建一个新的'BasicEffect'是没有意义的。 。好一个。 – 2010-12-16 14:12:07

+3

您看到的滞后是垃圾收集器正在运行并清理您正在创建的基本效果,并且因为它们是一次性对象,所以每个收集的对象都需要运行终结器。在游戏运行时,请谨慎使用new来分配非值类型。 – Empyrean 2010-12-18 11:07:46