ツインビーのオプション



ツインビーのオプションみたいなものを作ってみましょう。
自機の後ろについてくるやつです。自機の動きを完全になぞります。


サンプルコード

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System.Collections.Generic;

namespace Twinbee
{
    /// <summary>
    /// This is the main type for your game.
    /// </summary>
    public class Game1 : Game
    {
        // プレイヤー移動速度
        const float PlayerSpeed = 4.0f;
        // プレイヤーの位置の履歴の個数
        const int HistorySize = 40;

        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        // ぱっちぃのテクスチャ
        Texture2D texturePacchi;
        // かまトゥのテクスチャ
        Texture2D textureKamatoo;
        // プレイヤーの位置
        Vector2 playerPosition = new Vector2(200, 200);
        // プレイヤーの位置の履歴
        List<Vector2> positionHistory = new List<Vector2>();
        // オプションの位置
        Vector2 option0Position;
        Vector2 option1Position;
        Vector2 option2Position;
        Vector2 option3Position;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            // 履歴を初期化。とりあえず現在の位置で埋めておく。
            for (int i = 0; i < HistorySize; i++)
            {
                positionHistory.Add(playerPosition);
            }

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here

            // 画像を読み込む
            texturePacchi = Content.Load<Texture2D>("pacchi_32");
            textureKamatoo = Content.Load<Texture2D>("kamatoo_32");
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// game-specific content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();

            // TODO: Add your update logic here

            // プレイヤーの現在位置(移動前の位置)を履歴の先頭に挿入する
            positionHistory.Insert(0, playerPosition);

            // 最も古い履歴を除去する
            positionHistory.RemoveAt(positionHistory.Count - 1);

            // 上下左右が押されたらプレイヤーを移動させる
            if (Keyboard.GetState().IsKeyDown(Keys.Left))
            {
                playerPosition.X -= PlayerSpeed;
            }
            if (Keyboard.GetState().IsKeyDown(Keys.Right))
            {
                playerPosition.X += PlayerSpeed;
            }
            if (Keyboard.GetState().IsKeyDown(Keys.Up))
            {
                playerPosition.Y -= PlayerSpeed;
            }
            if (Keyboard.GetState().IsKeyDown(Keys.Down))
            {
                playerPosition.Y += PlayerSpeed;
            }

            // オプションの位置を更新する
            option0Position = positionHistory[9];
            option1Position = positionHistory[19];
            option2Position = positionHistory[29];
            option3Position = positionHistory[39];

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here

            spriteBatch.Begin();

            // オプションを描画
            spriteBatch.Draw(textureKamatoo, option3Position, Color.White);
            spriteBatch.Draw(textureKamatoo, option2Position, Color.White);
            spriteBatch.Draw(textureKamatoo, option1Position, Color.White);
            spriteBatch.Draw(textureKamatoo, option0Position, Color.White);

            // プレイヤーを描画
            spriteBatch.Draw(texturePacchi, playerPosition, Color.White);
         
            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}







解説

自機が移動した場所をなぞるためには、自機が移動した場所の履歴を記憶しておく必要があります。そのために今回はListを使っています。よって、冒頭に
using System.Collections.Generic;
を追加するのを忘れないようにしましょう。

positionHistoryという名前のListに自機の位置の履歴を格納しています。0番目が最も新しい履歴で、後ろにいくほど古いものとなります。

毎フレーム、自機を移動させる前に、位置をpositionHistoryの先頭に挿入しています。挿入しっぱなしだと、履歴がどんどん膨らんでいくので、末尾の最も古い履歴を除去しています。

あとは、最初のオプションは10フレーム前の履歴を参照し、次のオプションは20フレーム前の履歴を参照し、その次のオプションは30フレーム前の履歴を・・・とやってるだけです。



補足~循環バッファ

いまからするのは、動きのアルゴリズムには関係ない話で、データ構造についての話なのですが、今回、履歴を格納するのにListを使っていますが、実はこれはあまり好ましくありません。
Listは挿入や削除が遅いので、頻繁に挿入や削除が行われるのであれば、別のデータ構造を採用すべきです。
今回はデータ数が決まっていて、挿入や削除があるといっても、先頭と末尾にだけ行われます(途中への挿入や削除は行われない)。このようなケースでは、循環バッファと呼ばれる(またはリングバッファとも呼ばれる)データ構造が最適です。
残念ながら、C#には循環バッファが用意されていないため、自分で実装する必要がありそうです・・・(C#のQueueというクラスの内部実装は循環バッファだけど、先頭以外の要素にアクセスできないので今回は使えない)

まあぶっちゃけ、今回は要素数が40個程度なので、Listでもまったく問題にはならないです(要素数が多ければ多いほど、挿入や削除に時間がかかります)。

でも気になる人は、せっかくなので、循環バッファ、勉強してみてください。

汎用的な循環バッファを作ろうとすると、やや面倒ですが、今回のように用途が決まっているなら、特に難しいことはなく、配列を使ってちょちょいのちょいです。

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
// using System.Collections.Generic;←これもう不要

namespace Twinbee
{
    /// <summary>
    /// This is the main type for your game.
    /// </summary>
    public class Game1 : Game
    {
        // プレイヤー移動速度
        const float PlayerSpeed = 4.0f;

        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        // ぱっちぃのテクスチャ
        Texture2D texturePacchi;
        // かまトゥのテクスチャ
        Texture2D textureKamatoo;
        // プレイヤーの位置
        Vector2 playerPosition = new Vector2(200, 200);
        // プレイヤーの位置の履歴
        Vector2[] positionHistory = new Vector2[40];
        // 最新の履歴が格納されているindexを指す
        int topIndex = 0;
        // オプションの位置
        Vector2 option0Position;
        Vector2 option1Position;
        Vector2 option2Position;
        Vector2 option3Position;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            // 履歴を初期化。とりあえず現在の位置で埋めておく。
            for (int i = 0; i < positionHistory.Length; i++)
            {
                positionHistory[i] = playerPosition;
            }

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here

            // 画像を読み込む
            texturePacchi = Content.Load<Texture2D>("pacchi_32");
            textureKamatoo = Content.Load<Texture2D>("kamatoo_32");
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// game-specific content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();

            // TODO: Add your update logic here

            // 自機の現在の位置を記録する
            AddHistory(playerPosition);

            // 上下左右が押されたらプレイヤーを移動させる
            if (Keyboard.GetState().IsKeyDown(Keys.Left))
            {
                playerPosition.X -= PlayerSpeed;
            }
            if (Keyboard.GetState().IsKeyDown(Keys.Right))
            {
                playerPosition.X += PlayerSpeed;
            }
            if (Keyboard.GetState().IsKeyDown(Keys.Up))
            {
                playerPosition.Y -= PlayerSpeed;
            }
            if (Keyboard.GetState().IsKeyDown(Keys.Down))
            {
                playerPosition.Y += PlayerSpeed;
            }

            // オプションの位置を更新する
            option0Position = GetHistory(10); // 10フレーム前の履歴を参照
            option1Position = GetHistory(20); // 20フレーム前の履歴を参照
            option2Position = GetHistory(30); // 30フレーム前の履歴を参照
            option3Position = GetHistory(40); // 40フレーム前の履歴を参照

            base.Update(gameTime);
        }

        // 自機の位置の履歴を記録する
        void AddHistory(Vector2 position)
        {
            // 先頭を指しているindexをひとつ進める(末尾を超えたら、0に戻す)
            topIndex = (topIndex + 1) % positionHistory.Length;
            // 場所を格納する
            positionHistory[topIndex] = position;
        }

        // 自機の位置の履歴を取得する。
        // time : 何フレーム前の履歴か
        Vector2 GetHistory(int time)
        {
            time -= 1;

            return positionHistory[(positionHistory.Length + topIndex - time) % positionHistory.Length];
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here

            spriteBatch.Begin();

            // オプションを描画
            spriteBatch.Draw(textureKamatoo, option3Position, Color.White);
            spriteBatch.Draw(textureKamatoo, option2Position, Color.White);
            spriteBatch.Draw(textureKamatoo, option1Position, Color.White);
            spriteBatch.Draw(textureKamatoo, option0Position, Color.White);

            // プレイヤーを描画
            spriteBatch.Draw(texturePacchi, playerPosition, Color.White);
            
            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}


色んなオプションを作る目次へ戻る

0 件のコメント:

コメントを投稿