忍者ブログ

Memeplexes

プログラミング、3DCGとその他いろいろについて

XNA爆発チュートリアル その10 複数の爆発を表示

XNA爆発チュートリアル その9のつづきです。

なんだかグダグダになってきたので(笑)さっさと
このチュートリアルを終わらせるつもりで急ぎます。

今回は複数の爆発を表示できるようにしましょう。
普通ゲームでは複数のアイテムが同時に爆発するのは
よくあることだからです。

そこで、爆発のセットの方法を変えます

SetExplosion → AddExplosion

ExplosionRendererゲームコンポーネントの内部にExplosion構造体のリストを作り、
それにAddExplosionメソッドを使って追加するという方法にしましょう。
SetExplosionは廃止です。


ExplosionTest.cs
using Microsoft.Xna.Framework;


public class ExplosionTest : Game
{
    private GraphicsDeviceManager graphics;

    private ExplosionRenderer explosion;
    private float life;

    public ExplosionTest()
    {
        graphics = new GraphicsDeviceManager(this);
        explosion = new ExplosionRenderer(this);
        Matrix view = Matrix.CreateLookAt(
            new Vector3(0, 0, 4),
            new Vector3(),
            new Vector3(0, 1, 0)
            );
        Matrix projection = Matrix.CreatePerspectiveFieldOfView(
            MathHelper.ToRadians(45),
            (float)Window.ClientBounds.Width/Window.ClientBounds.Height,
            0.1f, 1000
            );
        explosion.SetCamera(view, projection);
        this.Components.Add(explosion);
    }


    protected override void Update(GameTime gameTime)
    {
        life -= (float)gameTime.ElapsedGameTime.TotalSeconds;

        if (life < 0)
        {
            life = 2;
            explosion.AddExplosion(new Explosion(new Vector3(), life));
            explosion.AddExplosion(new Explosion(new Vector3(1, 0, 0), life));
        }

        base.Update(gameTime);
    }

}


クライアント側はこんな感じです。
爆発を画面に表示したかったら、AddExplosionを使って追加するという方法をとります。
内部では寿命の尽きた爆発オブジェクトは自動的に取り除かれるのだということにしておきます。
そのため、使うのはAddExplosionメソッドだけです。
爆発オブジェクトを取り除くメソッドはありません。

次に、この実装を行います。
ExplosionRendererゲームコンポーネント内には爆発オブジェクトのリストが必要です。
これはSystem.Collections.Generics.Listを使えば良いでしょう。

ExplosionRenderer.cs
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using System.Collections.Generic;


public class ExplosionRenderer : Microsoft.Xna.Framework.DrawableGameComponent
{
    private Effect effect;
    private VertexDeclaration vertexDeclaration;
    private VertexVelocity[] vertices;

    private ContentManager content;
    private static System.Random random = new System.Random();

    private Matrix view;
    private Matrix projection;

    private List<Explosion> explosions = new List<Explosion>();


    public ExplosionRenderer(Game game)
        : base(game)
    {
        content = new ContentManager(game.Services);
    }


    public override void Initialize()
    {
        vertices = new VertexVelocity[30];

        for (int i = 0; i < vertices.Length; i++)
        {
            vertices[i].Velocity = randomVector3()/10;
        }

        base.Initialize();
    }

    Vector3 randomVector3()
    {
        return new Vector3(
            (float)(random.NextDouble() * 2 - 1),
            (float)(random.NextDouble() * 2 - 1),
            (float)(random.NextDouble() * 2 - 1)
            );
    }

    protected override void LoadGraphicsContent(bool loadAllContent)
    {
        if (loadAllContent)
        {
            effect = content.Load<Effect>("Content/ExplosionShader");
            effect.Parameters["ExplosionTexture"].SetValue(
                content.Load<Texture2D>("Content/explosion")
                );

            vertexDeclaration = new VertexDeclaration(
                GraphicsDevice,
                VertexVelocity.VertexElements
                );
        }
    }


    protected override void UnloadGraphicsContent(bool unloadAllContent)
    {
        if (unloadAllContent) { content.Unload(); }
    }

    public override void Update(GameTime gameTime)
    {
        for (int i = 0; i < explosions.Count; i++)
        {
            Explosion explosion = explosions[i];
            explosion.Update(gameTime);
            explosions[i] = explosion;
        }

        explosions.RemoveAll(
            delegate(Explosion explosion) { return explosion.Life < 0; }
            );
    }

    public override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        GraphicsDevice.RenderState.PointSize = 50;
        GraphicsDevice.RenderState.PointSpriteEnable = true;

        GraphicsDevice.RenderState.AlphaBlendEnable = true;
        GraphicsDevice.RenderState.SourceBlend = Blend.SourceAlpha;
        GraphicsDevice.RenderState.DestinationBlend = Blend.One;
        GraphicsDevice.RenderState.DepthBufferWriteEnable = false;

        GraphicsDevice.VertexDeclaration = vertexDeclaration;

        effect.Parameters["View"].SetValue(view);
        effect.Parameters["Projection"].SetValue(projection);

        foreach (Explosion explosion in explosions)
        { drawExplosion(explosion); }

        GraphicsDevice.RenderState.AlphaBlendEnable = false;
        GraphicsDevice.RenderState.DepthBufferWriteEnable = true;
    }

    private void drawExplosion(Explosion explosion)
    {
        effect.Parameters["Center"].SetValue(explosion.Center);
        effect.Parameters["Age"].SetValue(explosion.Age);
        effect.Parameters["StartLife"].SetValue(explosion.StartLife);

        effect.Begin();

        foreach (EffectPass pass in effect.CurrentTechnique.Passes)
        {
            pass.Begin();

            GraphicsDevice.DrawUserPrimitives<VertexVelocity>(
                PrimitiveType.PointList,
                vertices,
                0,
                vertices.Length
                );

            pass.End();
        }

        effect.End();
    }

    public void SetCamera(Matrix view, Matrix projection)
    {
        this.view = view;
        this.projection = projection;
    }

    public void AddExplosion(Explosion explosion)
    {
        this.explosions.Add(explosion);
    }
}


explosionTutorialDistance4.jpg
これで十分ですね。
ただ、このコードには気持ち悪いところがあります。
それは、爆発をUpdateするのに、次のように出来なかったことです:

foreach(Explosion explosion in explosions)
{ explosion.Update(gameTime); }


こっちのほうがはるかにスマートです。
にもかかわらずこう書くことが出来なかったのは、
Explosionがクラスではなく構造体だったからです。(参照型ではなく値型)
つまり、上のように書いた場合、アップデートされるのは爆発オブジェクトのコピーであって、
リストの中に入っている爆発オブジェクトではないのです。
つまり、爆発オブジェクトが全くアップデートされなくなってしまいます。

さて困りました。
パフォーマンスの観点からExplosionを構造体にするとこのような問題が生まれてしまいました。
Explosionを構造体からクラスに戻すべきでしょうか?
それとも後々のことを考えて構造体のままにしておくべきでしょうか?

ここは構造体からクラスに変えようと思います。
なぜなら、後のことを考えて現在のコードに複雑さを持ち込むのは
まずい場合が多いからです。
複雑さを持ち込むのは後でそこがパフォーマンスの
ボトルネックになってから考えても良いでしょう。

ExplosionRenderer.Updateメソッド
    public override void Update(GameTime gameTime)
    {
        foreach (Explosion explosion in explosions)
        { explosion.Update(gameTime); }

        explosions.RemoveAll(
            delegate(Explosion explosion) { return explosion.Life < 0; }
            );
    }

Explosion.cs
using Microsoft.Xna.Framework;

public class Explosion
{
    private float life;
    private float startLife;

    public float Life { get { return life; } }
    public float StartLife { get { return startLife; } }
    public float Age { get { return startLife - life; } }
    public Vector3 Center;

    public Explosion(Vector3 center, float life)
    {
        this.Center = center;
        this.life = life;
        this.startLife = life;
    }

    public void Update(GameTime gameTime)
    {
        life -= (float)gameTime.ElapsedGameTime.TotalSeconds;
    }
}





拍手[0回]

PR