引きずりオプション



引きずりオプションを作ってみましょう。

「引きずりオプション?」と思ったと思います。私が今、勝手に命名したものなので当然です。
まあ、上の画像を見てくれれば、やりたいことはわかってくれると思います。

オプションが自機のうしろについてくるため、一見するとグラディウスのオプションと同じように見えますが、よく見ると違います。一定の距離以上離れたときだけついてくるのです。一定の距離内にいる場合は動きません。引きずられているように見えるので、「引きずりオプション」と名付けました。

正直、2Dシューティングゲームでこういう動きのオプションは記憶に無いですが、ゲーム制作では、結構出てくる動きだと思います。3Dゲームでプレイヤーを追いかけるカメラの動きとかにも使えます。

考え方

下図の親を自機、子をオプションだと思ってください。
青い円は、オプションが引っ張られない範囲です。赤い矢印が半径です。



緑の矢印は、自機とオプションの距離です。
たとえ自機が移動しても、緑の長さ<赤の長さ の場合は、オプションは動きません。
直線の長さを調べるには、有名なピタゴラスの定理が有効ですが、それをやってくれるVector2.Distance()というメソッドがあるので、それを使いましょう。



自機が移動し、オプションが範囲外に出てしまったとします。
つまり 緑の長さ>赤の長さ です。
その場合、オプションを範囲内まで動かす必要があります。
ではどこに動かせば良いでしょうか?





ここです。





ここにオプションを移動させてあげます。
これを毎フレーム繰り返すと、引っ張って引きずっているように見えます。

さて、それでは、上記の位置はどうやって求めれば良いのでしょうか?




まず、上図の緑のベクトルを求めます。自機から見たオプションへの相対位置のベクトルです。これは、オプション位置 - 自機位置 で求まります。





次に、ベクトルを正規化します。ベクトルの正規化とは、難しい響きですが、ただ単に、長さを1にすることです。
ベクトルの各成分(xとy)を、それぞれベクトルの長さで割ってあげれば、長さが1になりますが、それをやってくれるNormalize()というメソッドがあるので、それを使いましょう。
なぜベクトルを正規化するのかというと、長さが1のほうが何かと計算に便利だからです。




最後に、正規化したベクトルに半径の長さをかければ、上図の緑のベクトルとなります。
(このために正規化しました)






サンプルコード

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace Trail
{
    /// <summary>
    /// This is the main type for your game.
    /// </summary>
    public class Game1 : Game
    {
        // プレイヤー移動速度
        const float PlayerSpeed = 5.0f;
        // オプションの距離
        const float OptionDistance = 60f;

        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        // ぱっちぃのテクスチャ
        Texture2D texturePacchi;
        // かまトゥのテクスチャ
        Texture2D textureKamatoo;
        // プレイヤーの位置
        Vector2 playerPosition = new Vector2(200, 200);
        // オプションの位置
        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

            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

            // 上下左右が押されたらプレイヤーを移動させる
            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 = CalcOptionPosition(option0Position, playerPosition);
            option1Position = CalcOptionPosition(option1Position, option0Position);
            option2Position = CalcOptionPosition(option2Position, option1Position);
            option3Position = CalcOptionPosition(option3Position, option2Position);

            base.Update(gameTime);
        }

        /// <summary>
        /// オプションのあるべき位置を計算する
        /// </summary>
        /// <param name="currentPosition">オプションの現在の位置</param>
        /// <param name="parentPosition">親の位置(1個目のオプションの親はプレイヤー、2個目のオプションの親は1個目のオプション)</param>
        /// <returns>あるべき位置</returns>
        Vector2 CalcOptionPosition(Vector2 currentPosition, Vector2 parentPosition)
        {
            // オプションと親の距離を算出
            float distance = Vector2.Distance(parentPosition, currentPosition);

            // 距離が一定以下の場合は、移動しない
            if (distance <= OptionDistance)
                return currentPosition;

            // 親から見たオプションへの相対位置のベクトルを算出
            Vector2 direction = currentPosition - parentPosition;
         
            // 正規化(長さを1に)
            direction.Normalize();

            // 親から上限まで離した位置があるべき場所
            return parentPosition + direction * OptionDistance;
        }

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


 



Lerpを組み合わせる

フォーメーションオプションを作ったときにも使ったLerpでヌルっと動かすテクニックは今回も有用です。
下記、黄色部分を変更します。

        Vector2 CalcOptionPosition(Vector2 currentPosition, Vector2 parentPosition)
        {
            // オプションと親の距離を算出
            float distance = Vector2.Distance(parentPosition, currentPosition);

            // 距離が一定以下の場合は、移動しない
            if (distance <= OptionDistance)
                return currentPosition;

            // 親から見たオプションへの相対位置のベクトルを算出
            Vector2 direction = currentPosition - parentPosition;
         
            // 正規化(長さを1に)
            direction.Normalize();

            // 親から上限まで離した位置があるべき場所
            Vector2 desired = parentPosition + direction * OptionDistance;

            // Lerpを使い、あるべき場所に少しずつ近づくように補正してから返却
            return Vector2.Lerp(currentPosition, desired, 0.2f);
        }

毎フレーム、目標地点に20%だけ近づくようにしました。



少し柔らかい動きになりました。ゴム紐っぽいというか。






オプションの数を増やしても面白い

オプションの数をめっちゃ増やしても面白いです。

これは、数を増やして、間隔などを調整した例です。


まるで紐やロープみたいな動きになります。
ぜひ挑戦してみてください。



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




0 件のコメント:

コメントを投稿