忍者ブログ

Memeplexes

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

XNA爆発チュートリアル その9 爆発の位置

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

前回は爆発を表すオブジェクトを作りました。
爆発の描画される寿命を管理するオブジェクトです。
しかしこれには足りないものがあるように思えます。

たとえば、爆発の位置です。
現在の作っているゲームコンポーネントの機能は、爆発を描画することですが、
これは位置を制御できません。
常に爆発は原点O(0, 0, 0)のまわりに描画されます。
これでは使い物になりません

現実には、ゲーム中のアイテムが壊れたときに爆発を表示しなければならないため、
爆発の位置をコントロールすることが出来なくてはいけないでしょう。
つまり、爆発を表す構造体Explosionには爆発の中心を表すフィールドが必要です。

そしてExplosionオブジェクトはクライアントコードであるGame側から
セットするようにすべきでしょう。
ExplosionRendererゲームコンポーネントクラスの責任ではありません。

使い方はこんな感じでしょう:

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.SetExplosion(new Explosion(new Vector3(), life));
        }

        base.Update(gameTime);
    }

}


爆発のセットはゲームクラスで行っています。
爆発を描画するゲームコンポーネントのExplosionRendererに
SetExplosionというメソッドを追加し、それを使って爆発オブジェクトをセットします。

爆発を表す構造体Explosionのコンストラクタも変わりました。
一番最初の引数に爆発の中心が追加されています。
これで爆発する場所を自由に決められるようになりました。(実装はまだですけどね)

とりあえずExplosion構造体のほうをこの変更に合わせましょう

Explosion.cs
using Microsoft.Xna.Framework;

public struct 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;
    }
}


つまり、爆発中心を表すCenterフィールドを追加しただけです。
(プロパティにしたほうがよかったかな?いやでもむやみに複雑化しても困ります)

次はこれを使うゲームコンポーネント、ExplosionRendererの変更です。
まずSetExplosionメソッドを追加して、さらにセットされた爆発の中心を読み込んでエフェクトにセットしなきゃいけません。
(ややこしいですね。もしかするともうちょっと作業を細分化したほうがよかったかもしれないと反省しつつ、続行です)

ExplosionRenderer.cs
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;


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 Explosion 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)
    {
        explosion.Update(gameTime);
    }

    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);

        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 SetExplosion(Explosion explosion)
    {
        this.explosion = explosion;
    }
}


最後に、HLSLで書くエフェクトファイルにグローバル変数Centerを
追加しなくてはいけません。

ExplosionShader.fx
float4x4 View;
float4x4 Projection;

float3 Center;
float Age;
float StartLife;

texture ExplosionTexture;

sampler explosionSampler = sampler_state
{
	Texture = <ExplosionTexture>;
};

struct ExplosionVertexShaderOutput
{
	float4 Position : POSITION;
	float4 Color : COLOR;
};

float4 ComputeColor(float normalizedAge)
{
	float4 color = 1;
	color.a *= normalizedAge * (1 - normalizedAge) * (1 - normalizedAge) * 6.7;
	return color;
}

ExplosionVertexShaderOutput ExplosionVertexShader(float4 velocity:COLOR)
{
	ExplosionVertexShaderOutput output;
	float4 worldPosition = float4(velocity.xyz * Age + Center, 1);
	output.Position = mul(worldPosition, mul(View, Projection));
	output.Color = ComputeColor(Age / StartLife);
	return output;
}

float4 ExplosionPixelShader(
	float2 textureCoordinate:TEXCOORD,
	float4 color:COLOR
	):COLOR
{
	return tex2D(explosionSampler, textureCoordinate) * color;
}

technique ExplosionShaderTechnique
{
	pass P0
	{
		VertexShader = compile vs_2_0 ExplosionVertexShader();
		PixelShader = compile ps_2_0 ExplosionPixelShader();
	}
}



これでひとまずOKです。
ウィンドウに描画される爆発は以前と変わりませんが、
ソースコードに柔軟性が生まれました。
爆発の位置を色々と変えることが出来ます。
ためしに、右に1ずらしてみましょう。

explosion.SetExplosion(new Explosion(new Vector3(1, 0, 0), life));

explosionTutorialExplosionAtO.jpg(ずらす前。爆発の中心は(0, 0, 0))

explosionTutorialExplosionMoved.jpg(ずらした後。爆発の中心は(1, 0, 0))

うまくずれています。
これで好きなところに爆発を描画することができるようになりました。

拍手[0回]

PR