<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>タイルマップ | アリッシアの朝</title>
	<atom:link href="https://alicia-ing.com/tag/%e3%82%bf%e3%82%a4%e3%83%ab%e3%83%9e%e3%83%83%e3%83%97/feed/" rel="self" type="application/rss+xml" />
	<link>https://alicia-ing.com</link>
	<description></description>
	<lastBuildDate>Sun, 27 Sep 2026 04:51:21 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1.4</generator>

<image>
	<url>https://alicia-ing.com/wp-content/uploads/2023/05/cropped-alicia-32x32.webp</url>
	<title>タイルマップ | アリッシアの朝</title>
	<link>https://alicia-ing.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>【Unity】矢印キーで2Dプレイヤーを1マスずつ移動</title>
		<link>https://alicia-ing.com/programming/unity/2dplayermove/</link>
					<comments>https://alicia-ing.com/programming/unity/2dplayermove/#respond</comments>
		
		<dc:creator><![CDATA[アリッシア]]></dc:creator>
		<pubDate>Sun, 27 Sep 2026 04:43:53 +0000</pubDate>
				<category><![CDATA[Unity]]></category>
		<category><![CDATA[タイルマップ]]></category>
		<guid isPermaLink="false">https://alicia-ing.com/?p=8971</guid>

					<description><![CDATA[昔のRPGのように、キャラクターがマス目にそってカクカクと動く移動するゲームは3Dゲームよりも制作の負担もなく現在もレトロゲームや同人ゲームとして人気が強いです。 Tilemapでマップを作ったあと、「プレイヤーを1マス [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-cocoon-blocks-label-box-1 label-box block-box not-nested-style cocoon-block-label-box"><div class="label-box-label block-box-label box-label fab-flag"><span class="label-box-label-text block-box-label-text box-label-text">本記事を読むと以下の実行ができます</span></div><div class="label-box-content block-box-content box-content">
<p class="wp-block-paragraph">矢印キーで2Dプレイヤーをタイル1マスずつ動かし、長押しでの連続移動と、進む方向に合わせた向きの画像の切り替えができるようになります。</p>



<figure class="wp-block-image size-full"><img decoding="async" src="https://alicia-ing.com/wp-content/uploads/2026/09/complete-1.webp" alt=""/></figure>
</div></div>



<p class="wp-block-paragraph">昔のRPGのように、<strong>キャラクターがマス目にそってカクカクと動く移動するゲーム</strong>は3Dゲームよりも制作の負担もなく現在もレトロゲームや同人ゲームとして人気が強いです。</p>



<p class="wp-block-paragraph">Tilemapでマップを作ったあと、「プレイヤーを1マスずつ動かすにはどうすればいいの？」とつまずく人も多いはずです。</p>



<p class="wp-block-paragraph">本記事では、2dキャラクターの実装として、Input.GetKeyを使ったキー入力から1マスずつの移動・向きの切り替えまでを解説します。キーを押しっぱなしにしたときの連続移動や、2つのキーを同時に押したときの優先順位など、実際に遊ぶと気になる動きにも対応しています。</p>



<div class="wp-block-cocoon-blocks-micro-text micro-text micro-copy micro-top"><span class="micro-text-content micro-content"><span class="micro-text-icon micro-icon fab-info-circle"></span>3Dのキャラクター移動を解説しています。</span></div>



<div class="wp-block-cocoon-blocks-blogcard blogcard-type bct-together">

<a target="_self" href="https://alicia-ing.com/programming/unity/3dplayermove/" title="【Unity】Rigidbody+CapsuleColliderを用いたプレイヤー移動" class="blogcard-wrap internal-blogcard-wrap a-wrap cf"><div class="blogcard internal-blogcard ib-left cf"><div class="blogcard-label internal-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail internal-blogcard-thumbnail"><img fetchpriority="high" decoding="async" width="320" height="180" src="https://alicia-ing.com/wp-content/uploads/2026/07/3dplayermove-320x180.webp" class="blogcard-thumb-image internal-blogcard-thumb-image wp-post-image" alt="" srcset="https://alicia-ing.com/wp-content/uploads/2026/07/3dplayermove-320x180.webp 320w, https://alicia-ing.com/wp-content/uploads/2026/07/3dplayermove-240x135.webp 240w, https://alicia-ing.com/wp-content/uploads/2026/07/3dplayermove-640x360.webp 640w" sizes="(max-width: 320px) 100vw, 320px" /></figure><div class="blogcard-content internal-blogcard-content"><div class="blogcard-title internal-blogcard-title">【Unity】Rigidbody+CapsuleColliderを用いたプレイヤー移動</div><div class="blogcard-snippet internal-blogcard-snippet">UnityでCharacterControllerからRigidbody+CapsuleColliderへ移動処理を移行する方法を解説。カメラ相対移動、FixedUpdateでの速度制御、移行の判断基準まで紹介します。</div></div><div class="blogcard-footer internal-blogcard-footer cf"><div class="blogcard-site internal-blogcard-site"><div class="blogcard-favicon internal-blogcard-favicon"><img decoding="async" src="https://www.google.com/s2/favicons?domain=https://alicia-ing.com" alt="" class="blogcard-favicon-image internal-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain internal-blogcard-domain">alicia-ing.com</div></div><div class="blogcard-date internal-blogcard-date"><div class="blogcard-post-date internal-blogcard-post-date">2026.07.13</div></div></div></div></a>
</div>



<div class="wp-block-cocoon-blocks-label-box-1 label-box block-box cocoon-block-label-box"><div class="label-box-label block-box-label box-label fab-check"><span class="label-box-label-text block-box-label-text box-label-text">本記事は次の人におすすめ</span></div><div class="label-box-content block-box-content box-content">
<ul class="wp-block-list">
<li>矢印キーで2Dキャラクターを1マスずつ動かしたい人</li>



<li>Tilemapで作ったマップの上をプレイヤーに歩かせたい人</li>



<li>unity キー 入力（GetKey・GetKeyDown）の違いと使い分けを知りたい人</li>



<li>キーを押しっぱなしにしたときに、ちょうど良い速さで連続移動させたい人</li>



<li>進む方向に合わせてキャラクターの画像を上下左右に切り替えたい人</li>
</ul>
</div></div>



<div id="rtoc-mokuji-wrapper" class="rtoc-mokuji-content frame3 preset1 animation-none rtoc_open default" data-id="8971" data-theme="Cocoon Child">
			<div id="rtoc-mokuji-title" class=" rtoc_left">
			<button class="rtoc_open_close rtoc_open"></button>
			<span>目次</span>
			</div><ol class="rtoc-mokuji decimal_ol level-1"><li class="rtoc-item"><a href="#rtoc-1">Input.GetKey（キー入力）</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-2">GetKey・GetKeyDown・GetKeyUpの違い</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-3">event Action（C#のイベント）で処理をつなぐ</a></li><li class="rtoc-item"><a href="#rtoc-4">SpriteRenderer.spriteで画像を差し替える</a></li><li class="rtoc-item"><a href="#rtoc-5">矢印キーで1マスずつ動く2Dプレイヤー移動</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-6">ソースコード</a></li><li class="rtoc-item"><a href="#rtoc-7">解説</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-8">実装</a></li><li class="rtoc-item"><a href="#rtoc-9">まとめ</a></li></ol></div><h2 id="rtoc-1"  class="wp-block-heading">Input.GetKey（キー入力）</h2>



<figure class="wp-block-image size-full"><img decoding="async" width="1672" height="941" src="https://alicia-ing.com/wp-content/uploads/2026/09/input-getkey.webp" alt="" class="wp-image-8981" srcset="https://alicia-ing.com/wp-content/uploads/2026/09/input-getkey.webp 1672w, https://alicia-ing.com/wp-content/uploads/2026/09/input-getkey-300x169.webp 300w, https://alicia-ing.com/wp-content/uploads/2026/09/input-getkey-768x432.webp 768w, https://alicia-ing.com/wp-content/uploads/2026/09/input-getkey-1024x576.webp 1024w, https://alicia-ing.com/wp-content/uploads/2026/09/input-getkey-1536x864.webp 1536w, https://alicia-ing.com/wp-content/uploads/2026/09/input-getkey-240x135.webp 240w, https://alicia-ing.com/wp-content/uploads/2026/09/input-getkey-320x180.webp 320w, https://alicia-ing.com/wp-content/uploads/2026/09/input-getkey-640x360.webp 640w" sizes="(max-width: 1672px) 100vw, 1672px" /></figure>



<p class="wp-block-paragraph">Input.GetKeyは、<strong>キーボードのキーが押されているかどうか</strong>を調べる関数です。矢印キーでキャラクターを動かす、スペースキーでジャンプする、Escキーでメニューを開くなど、<strong>キーボードで操作するゲーム</strong>のほとんどで使われます。</p>



<p class="wp-block-paragraph">使い方は、調べたいキーをKeyCodeで指定するだけです。矢印キーはそれぞれ次のKeyCodeに対応しています。</p>



<figure class="wp-block-table"><div class="scrollable-table"><table class="has-fixed-layout"><thead><tr><th>キー</th><th>Keycode</th></tr></thead><tbody><tr><td>↑　上</td><td>KeyCode.UpArrow</td></tr><tr><td>↓　下</td><td>KeyCode.DownArrow</td></tr><tr><td>→　右</td><td>KeyCode.RightArrow</td></tr><tr><td>←　左</td><td>KeyCode.LeftArrow</td></tr></tbody></table></div></figure>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-csharp" data-lang="C#"><code>if (Input.GetKey(KeyCode.RightArrow))
{
    // →キーが押されている間、毎フレーム実行される
}</code></pre></div>



<p class="wp-block-paragraph">キー入力の処理は、毎フレーム呼ばれるUpdate()の中に書きます。</p>



<p class="wp-block-paragraph">参考：<a target="_self" href="https://docs.unity3d.com/ja/current/ScriptReference/Input.GetKey.html">Input.GetKey &#8211; Unity スクリプトリファレンス</a></p>



<h3 id="rtoc-2"  class="wp-block-heading">GetKey・GetKeyDown・GetKeyUpの違い</h3>



<p class="wp-block-paragraph">キー入力を調べる関数は3種類あり、trueを返すタイミングが違います。</p>



<figure class="wp-block-table"><div class="scrollable-table"><table class="has-fixed-layout"><thead><tr><th class="has-text-align-left" data-align="left">関数</th><th class="has-text-align-left" data-align="left">trueになるタイミング</th><th class="has-text-align-left" data-align="left">主な用途</th></tr></thead><tbody><tr><td>Input.GetKey</td><td>キーを押している間ずっと（毎フレーム）</td><td>押しっぱなしで動き続ける移動・ダッシュ</td></tr><tr><td>Input.GetKeyDown</td><td>キーを押した瞬間の1フレームだけ</td><td>ジャンプ・決定・1回だけの移動</td></tr><tr><td>Input.GetKeyUp</td><td>キーを離した瞬間の1フレームだけ</td><td>ため攻撃の発射・長押しの終了</td></tr></tbody></table></div></figure>



<p class="wp-block-paragraph">1マスずつ動かしたい場合、GetKeyだけを使うと毎フレーム1マス進んでしまい、一瞬で画面の端まで飛んでいってしまいます。反対にGetKeyDownだけを使うと、押すたびに1マスしか進まず、長い距離を歩くときにキーを何度も叩くことになります。</p>



<p class="wp-block-paragraph">そこで本記事のコードでは、2つを組み合わせています。</p>



<ul class="wp-block-list">
<li><strong>GetKeyDown：</strong> どのキーが「新しく押されたか」を調べる</li>



<li><strong>GetKey：</strong> そのキーが「まだ押され続けているか」を調べ、一定の間隔で連続移動する</li>
</ul>



<h2 id="rtoc-3"  class="wp-block-heading">event Action（C#のイベント）で処理をつなぐ</h2>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1672" height="941" src="https://alicia-ing.com/wp-content/uploads/2026/09/event-action.webp" alt="" class="wp-image-8982" srcset="https://alicia-ing.com/wp-content/uploads/2026/09/event-action.webp 1672w, https://alicia-ing.com/wp-content/uploads/2026/09/event-action-300x169.webp 300w, https://alicia-ing.com/wp-content/uploads/2026/09/event-action-768x432.webp 768w, https://alicia-ing.com/wp-content/uploads/2026/09/event-action-1024x576.webp 1024w, https://alicia-ing.com/wp-content/uploads/2026/09/event-action-1536x864.webp 1536w, https://alicia-ing.com/wp-content/uploads/2026/09/event-action-240x135.webp 240w, https://alicia-ing.com/wp-content/uploads/2026/09/event-action-320x180.webp 320w, https://alicia-ing.com/wp-content/uploads/2026/09/event-action-640x360.webp 640w" sizes="(max-width: 1672px) 100vw, 1672px" /></figure>



<p class="wp-block-paragraph">eventは、<strong>「何かが起きたこと」を他のスクリプトに知らせるためのC#の仕組み</strong>です。Actionと組み合わせると、知らせるときに値（移動方向など）も一緒に渡せます。</p>



<p class="wp-block-paragraph">例えば「キーが押された」ことを入力のスクリプトが知らせ、それを受け取った移動のスクリプトがプレイヤーを動かす、という使い方をします。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-csharp" data-lang="C#"><code>// 知らせる側
public event Action&lt;Vector3&gt; MoveRequested;   // Vector3（方向）を一緒に渡すイベント
MoveRequested?.Invoke(Vector3.up);            // 登録されている処理をまとめて呼ぶ

// 受け取る側
input.MoveRequested += OnMoveRequested;       // 登録
input.MoveRequested -= OnMoveRequested;       // 解除</code></pre></div>



<figure class="wp-block-table"><div class="scrollable-table"><table class="has-fixed-layout"><thead><tr><th class="has-text-align-left" data-align="left">書き方</th><th class="has-text-align-left" data-align="left">意味</th></tr></thead><tbody><tr><td>event Action</td><td>値を渡さないイベント</td></tr><tr><td>event Action&lt;T></td><td>値を1つ渡すイベント</td></tr><tr><td>event Action&lt;T1, T2></td><td>値を2つ渡すイベント</td></tr><tr><td>?.Invoke(&#8230;)</td><td>登録している処理があれば呼び出す（誰も登録していなければ何もしない）</td></tr></tbody></table></div></figure>



<p class="wp-block-paragraph">イベントを使うと、入力・移動・画像の切り替えを別々のスクリプトに分けられます。それぞれのスクリプトはお互いの中身を知らなくてよいため、後から「NPCにも同じ移動を使いたい」「入力をゲームパッドに変えたい」となったときに、一部だけを差し替えられます。</p>



<p class="wp-block-paragraph">なお、Unityには<strong>Inspectorから登録できるUnityEvent</strong>もあります。本記事ではコードの中だけで完結させるため、C#のeventを使っています。</p>



<p class="wp-block-paragraph">参考：<a target="_self" href="https://learn.microsoft.com/ja-jp/dotnet/csharp/programming-guide/events/">イベント &#8211; C# プログラミング ガイド（Microsoft Learn）</a></p>



<h2 id="rtoc-4"  class="wp-block-heading">SpriteRenderer.spriteで画像を差し替える</h2>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1672" height="941" src="https://alicia-ing.com/wp-content/uploads/2026/09/spriteRenderer.webp" alt="" class="wp-image-8983" srcset="https://alicia-ing.com/wp-content/uploads/2026/09/spriteRenderer.webp 1672w, https://alicia-ing.com/wp-content/uploads/2026/09/spriteRenderer-300x169.webp 300w, https://alicia-ing.com/wp-content/uploads/2026/09/spriteRenderer-768x432.webp 768w, https://alicia-ing.com/wp-content/uploads/2026/09/spriteRenderer-1024x576.webp 1024w, https://alicia-ing.com/wp-content/uploads/2026/09/spriteRenderer-240x135.webp 240w, https://alicia-ing.com/wp-content/uploads/2026/09/spriteRenderer-1536x864.webp 1536w, https://alicia-ing.com/wp-content/uploads/2026/09/spriteRenderer-320x180.webp 320w, https://alicia-ing.com/wp-content/uploads/2026/09/spriteRenderer-640x360.webp 640w" sizes="(max-width: 1672px) 100vw, 1672px" /></figure>



<p class="wp-block-paragraph">SpriteRendererは、<strong>2Dの画像（スプライト）を画面に表示するコンポーネント</strong>です。<br>spriteプロパティに別のスプライトを代入すると、表示している画像をその場で差し替えられます。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-csharp" data-lang="C#"><code>playerRenderer.sprite = spriteUp;   // 上向きの画像に切り替える</code></pre></div>



<p class="wp-block-paragraph">キャラクターの向きを変える方法には、ほかにAnimatorでアニメーションを切り替える方法もあります。</p>



<p class="wp-block-paragraph"><strong>歩きのアニメーションまで作り込みたい場合はAnimatorが向いています</strong>が、上下左右の4枚の画像を切り替えるだけなら、spriteを差し替える方法の方が設定が少なく済みます。</p>



<figure class="wp-block-table"><div class="scrollable-table"><table class="has-fixed-layout"><thead><tr><th class="has-text-align-left" data-align="left">方法</th><th class="has-text-align-left" data-align="left">向いている場面</th></tr></thead><tbody><tr><td>SpriteRenderer.spriteの差し替え</td><td>上下左右の静止画を切り替えるだけのとき（本記事）</td></tr><tr><td>Animator（Blend Tree）</td><td>方向ごとに歩きのアニメーションを付けたいとき</td></tr></tbody></table></div></figure>



<div class="wp-block-cocoon-blocks-micro-text micro-text micro-copy micro-top"><span class="micro-text-content micro-content"><span class="micro-text-icon micro-icon fab-info-circle"></span>オブジェクトが表示されないエラーについて紹介しています。</span></div>



<div class="wp-block-cocoon-blocks-blogcard blogcard-type bct-together">

<a target="_self" href="https://alicia-ing.com/programming/unity/render-camera/" title="【Unity】2D/3Dオブジェクトが表示されない原因と対処方法" class="blogcard-wrap internal-blogcard-wrap a-wrap cf"><div class="blogcard internal-blogcard ib-left cf"><div class="blogcard-label internal-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail internal-blogcard-thumbnail"><img loading="lazy" decoding="async" width="160" height="90" src="https://alicia-ing.com/wp-content/uploads/2024/06/Screen-Space-Camera-160x90.webp" class="blogcard-thumb-image internal-blogcard-thumb-image wp-post-image" alt="" srcset="https://alicia-ing.com/wp-content/uploads/2024/06/Screen-Space-Camera-160x90.webp 160w, https://alicia-ing.com/wp-content/uploads/2024/06/Screen-Space-Camera-120x68.webp 120w, https://alicia-ing.com/wp-content/uploads/2024/06/Screen-Space-Camera-320x180.webp 320w" sizes="(max-width: 160px) 100vw, 160px" /></figure><div class="blogcard-content internal-blogcard-content"><div class="blogcard-title internal-blogcard-title">【Unity】2D/3Dオブジェクトが表示されない原因と対処方法</div><div class="blogcard-snippet internal-blogcard-snippet">2D/3Dオブジェクトが表示されない原因は、カメラワークの不具合が考えられます。「Screen Space - Camera」にして、MainCameraをアタッチすると正しく表示されます。</div></div><div class="blogcard-footer internal-blogcard-footer cf"><div class="blogcard-site internal-blogcard-site"><div class="blogcard-favicon internal-blogcard-favicon"><img decoding="async" src="https://www.google.com/s2/favicons?domain=https://alicia-ing.com" alt="" class="blogcard-favicon-image internal-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain internal-blogcard-domain">alicia-ing.com</div></div><div class="blogcard-date internal-blogcard-date"><div class="blogcard-post-date internal-blogcard-post-date">2024.11.10</div></div></div></div></a>
</div>



<p class="wp-block-paragraph">参考：<a target="_self" href="https://docs.unity3d.com/ja/current/ScriptReference/SpriteRenderer-sprite.html">SpriteRenderer.sprite &#8211; Unity スクリプトリファレンス</a></p>



<h2 id="rtoc-5"  class="wp-block-heading">矢印キーで1マスずつ動く2Dプレイヤー移動</h2>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1672" height="941" src="https://alicia-ing.com/wp-content/uploads/2026/09/keymove.webp" alt="" class="wp-image-8984" srcset="https://alicia-ing.com/wp-content/uploads/2026/09/keymove.webp 1672w, https://alicia-ing.com/wp-content/uploads/2026/09/keymove-300x169.webp 300w, https://alicia-ing.com/wp-content/uploads/2026/09/keymove-768x432.webp 768w, https://alicia-ing.com/wp-content/uploads/2026/09/keymove-1024x576.webp 1024w, https://alicia-ing.com/wp-content/uploads/2026/09/keymove-240x135.webp 240w, https://alicia-ing.com/wp-content/uploads/2026/09/keymove-320x180.webp 320w, https://alicia-ing.com/wp-content/uploads/2026/09/keymove-1536x864.webp 1536w, https://alicia-ing.com/wp-content/uploads/2026/09/keymove-640x360.webp 640w" sizes="(max-width: 1672px) 100vw, 1672px" /></figure>



<p class="wp-block-paragraph">ここまでに説明したInput.GetKey・event Action・SpriteRenderer.spriteを組み合わせて、Tilemapの上を1マスずつ歩く2Dプレイヤーを作ります。実装する動きは次のとおりです。</p>



<ul class="wp-block-list">
<li><strong>1マスずつ移動：</strong> 矢印キーを押すと、上下左右に1マス分だけ移動する</li>



<li><strong>長押しで連続移動：</strong> キーを押しっぱなしにすると、少し待ってから一定の間隔で進み続ける</li>



<li><strong>同時押しの優先：</strong> 2つのキーを押したときは、後から押したキーの方向へ進む（斜めには進まない）</li>



<li><strong>向きの切り替え：</strong> 進む方向に合わせて、キャラクターの画像を上下左右に切り替える</li>



<li><strong>止まったときの表示：</strong> キーを離したら「待機画像」か「最後に向いた方向」のどちらかを表示する</li>
</ul>



<p class="wp-block-paragraph">処理は役割ごとに5つのスクリプトに分けています。</p>



<figure class="wp-block-table"><div class="scrollable-table"><table class="has-fixed-layout"><thead><tr><th class="has-text-align-left" data-align="left">スクリプト</th><th class="has-text-align-left" data-align="left">役割</th></tr></thead><tbody><tr><td>PlayerInput.cs</td><td>矢印キーの入力から動く方向を決める</td></tr><tr><td>GridMover.cs</td><td>対象を1マス動かし「動こうとした」「動いた」と知らせる</td></tr><tr><td>PlayerDirectionSprite.cs</td><td>向きに合わせて画像を差し替える</td></tr><tr><td>PlayerSpawner.cs</td><td>ゲーム開始時の位置と向きを決める</td></tr><tr><td>PlayerController.cs</td><td>上の4つをイベントでつなぐ</td></tr></tbody></table></div></figure>



<h3 id="rtoc-6"  class="wp-block-heading">ソースコード</h3>



<h4 class="wp-block-heading">PlayerInput.cs</h4>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-csharp" data-lang="C#"><code>using System;
using System.Collections.Generic;
using UnityEngine;

/// &lt;summary&gt;
/// 矢印キーから移動の要求
/// &lt;/summary&gt;
public class PlayerInput : MonoBehaviour
{
    [SerializeField] private float repeatDelay = 0.2f;     
    [SerializeField] private float repeatInterval = 0.1f;  
    private float repeatTimer;      

    public event Action&lt;Vector3&gt; MoveRequested; 
    public event Action Released;              
    //入力キーと方向を対応させる
    private static readonly (KeyCode key, Vector3 direction)[] bindings =
    {
        (KeyCode.UpArrow, Vector3.up),
        (KeyCode.DownArrow, Vector3.down),
        (KeyCode.RightArrow, Vector3.right),
        (KeyCode.LeftArrow, Vector3.left),
    };

    // 押された順に並べたbindingsの添字。最後が現在有効なキー
    private readonly List&lt;int&gt; heldKeys = new List&lt;int&gt;();
    private const int None = -1;  // キーを押していない
    private int CurrentIndex =&gt; heldKeys.Count &gt; 0 ? heldKeys[heldKeys.Count - 1] : None;

    private void Update()
    {
        int previousIndex = CurrentIndex;

        heldKeys.RemoveAll(i =&gt; !Input.GetKey(bindings[i].key));
        for (int i = 0; i &lt; bindings.Length; i++)
        {
            if (Input.GetKeyDown(bindings[i].key) && !heldKeys.Contains(i))
                heldKeys.Add(i);
        }
        
        int currentIndex = CurrentIndex;
        if (currentIndex == None)
        {
            if (previousIndex != None) Released?.Invoke();
            return;
        }

        if (currentIndex != previousIndex)
        {
            repeatTimer = repeatDelay;
            MoveRequested?.Invoke(bindings[currentIndex].direction);
            return;
        }

        repeatTimer -= Time.deltaTime;
        if (repeatTimer &lt;= 0f)
        {
            repeatTimer = repeatInterval;
            MoveRequested?.Invoke(bindings[currentIndex].direction);
        }
    }
}</code></pre></div>



<h4 class="wp-block-heading">GridMover.cs</h4>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-csharp" data-lang="C#"><code>using System;
using UnityEngine;

/// &lt;summary&gt;
/// 対象を1マスずつ動かす。向き・移動の通知を行う
/// &lt;/summary&gt;
public class GridMover : MonoBehaviour
{
    [SerializeField] private Transform target;
    [SerializeField] private float gridSize = 1f;

    public event Action&lt;Vector3&gt; MoveAttempted;
    public event Action&lt;Vector3, Vector3&gt; Moved;

    //移動処理
    public bool TryMove(Vector3 direction)
    {
        if (direction == Vector3.zero || target == null) return false;

        MoveAttempted?.Invoke(direction);

        Vector3 nextPos = target.position + direction * gridSize; //移動先

        target.position = nextPos;  //位置更新
        Moved?.Invoke(nextPos, direction);
        return true;
    }
}
</code></pre></div>



<h4 class="wp-block-heading">PlayerDirectionSprite.cs</h4>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-csharp" data-lang="C#"><code>using UnityEngine;

/// &lt;summary&gt;
/// プレイヤーの進行で画像差し替え
/// &lt;/summary&gt;
public class PlayerDirectionSprite : MonoBehaviour
{
    //止まっているときの状態
    private enum IdleFacingMode
    {
        IdleSprite, //待機
        LastDirection //最後に向いている方向
    }

    [SerializeField] private SpriteRenderer playerRenderer;
    [SerializeField] private Sprite spriteIdle;
    [SerializeField] private Sprite spriteUp;
    [SerializeField] private Sprite spriteDown;
    [SerializeField] private Sprite spriteLeft;
    [SerializeField] private Sprite spriteRight;
    [SerializeField] private IdleFacingMode idleFacingMode = IdleFacingMode.LastDirection;

    private Vector3 lastFacingDirection = Vector3.zero;

    //指定した方向を向く
    public void Face(Vector3 direction)
    {
        if (direction == Vector3.zero) return; 

        lastFacingDirection = direction;
        SetSprite(GetSpriteForDirection(direction));
    }

    //止まったときの画像にする
    public void ShowIdle()
    {
        bool hasLastFacing = lastFacingDirection != Vector3.zero;
        bool keepLastFacing = idleFacingMode == IdleFacingMode.LastDirection && hasLastFacing;

        SetSprite(keepLastFacing ? GetSpriteForDirection(lastFacingDirection) : null);
    }

    //画像の差し替え
    private void SetSprite(Sprite sprite)
    {
        if (playerRenderer == null) return;

        Sprite nextSprite = sprite ?? spriteIdle;
        if (nextSprite != null && playerRenderer.sprite != nextSprite)
            playerRenderer.sprite = nextSprite;
    }

    //対応する画像を呼び出す
    private Sprite GetSpriteForDirection(Vector3 direction)
    {
        if (direction == Vector3.up && spriteUp != null) return spriteUp;
        if (direction == Vector3.down && spriteDown != null) return spriteDown;
        if (direction == Vector3.left && spriteLeft != null) return spriteLeft;
        if (direction == Vector3.right && spriteRight != null) return spriteRight;
    
        return null;
    }
}
</code></pre></div>



<h4 class="wp-block-heading">PlayerSpawner.cs</h4>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-csharp" data-lang="C#"><code>using UnityEngine;

/// &lt;summary&gt;
/// シーン開始時のプレイヤーの位置と向きを決める
/// &lt;/summary&gt;
public class PlayerSpawner : MonoBehaviour
{
    [SerializeField] private Transform target;
    [SerializeField] private Vector3 startPosition = new Vector3(0.5f, 0.5f, 0f); 

    // 開始位置に置き、開始時の向きを startFacing に入れる
    public void Spawn(out Vector3 startFacing)
    {
        if (target == null) target = transform;

        target.position = startPosition;
        startFacing = Vector3.zero;
    }
}
</code></pre></div>



<p class="wp-block-paragraph"></p>



<h4 class="wp-block-heading">PlayerController.cs</h4>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-csharp" data-lang="C#"><code>using UnityEngine;

/// &lt;summary&gt;
/// プレイヤーの各コンポーネントの接続
/// 入力 → 移動 → 向きの画像
/// &lt;/summary&gt;
public class PlayerController : MonoBehaviour
{
    [SerializeField] private PlayerInput input;
    [SerializeField] private GridMover mover;
    [SerializeField] private PlayerSpawner spawner;
    [SerializeField] private PlayerDirectionSprite directionSprite; // 向きスプライト制御

    // イベントの登録/解除
    private void OnEnable()
    {
        if (input != null)
        {
            input.MoveRequested += OnMoveRequested; 
            input.Released += OnReleased;
        }
        if (mover != null)
        {
            mover.MoveAttempted += OnMoveAttempted;
        }
    }

    private void OnDisable()
    {
        if (input != null)
        {
            input.MoveRequested -= OnMoveRequested;
            input.Released -= OnReleased;
        }
        if (mover != null)
        {
            mover.MoveAttempted -= OnMoveAttempted;
        }
    }

    private void Start()
    {
        Vector3 startFacing = Vector3.zero;
        if (spawner != null) spawner.Spawn(out startFacing);

        if (directionSprite == null) return;
        if (startFacing == Vector3.zero) directionSprite.ShowIdle();
        else directionSprite.Face(startFacing);
    }

    ///イベントを受け取る
    private void OnMoveRequested(Vector3 direction) =&gt; mover?.TryMove(direction);
    private void OnReleased() =&gt; directionSprite?.ShowIdle();
    private void OnMoveAttempted(Vector3 direction) =&gt; directionSprite?.Face(direction);
}
</code></pre></div>



<h3 id="rtoc-7"  class="wp-block-heading">解説</h3>



<ul class="wp-block-list">
<li><strong>名前空間（モジュール）</strong></li>
</ul>



<figure class="wp-block-table"><div class="scrollable-table"><table class="has-fixed-layout"><thead><tr><th class="has-text-align-left" data-align="left">名前空間</th><th class="has-text-align-left" data-align="left">使っている理由</th></tr></thead><tbody><tr><td>UnityEngine</td><td>MonoBehaviour・Input・Vector3・SpriteRendererなど、Unityの基本機能を使うため</td></tr><tr><td>System</td><td>イベントの型Actionを使うため（PlayerInput・GridMover）</td></tr><tr><td>System.Collections.Generic</td><td>押しているキーを順番に覚えるList&lt;int>を使うため（PlayerInput）</td></tr></tbody></table></div></figure>



<ul class="wp-block-list">
<li><strong><strong>イベント</strong></strong></li>
</ul>



<figure class="wp-block-table"><div class="scrollable-table"><table class="has-fixed-layout"><thead><tr><th class="has-text-align-left" data-align="left">スクリプト</th><th class="has-text-align-left" data-align="left">イベント</th><th class="has-text-align-left" data-align="left">知らせる内容</th></tr></thead><tbody><tr><td>PlayerInput</td><td>MoveRequested</td><td>「この方向に動きたい」（方向）</td></tr><tr><td>PlayerInput</td><td>Released</td><td>「矢印キーがすべて離された」</td></tr><tr><td>GridMover</td><td>MoveAttempted</td><td>「この方向に動こうとした」（方向）</td></tr><tr><td>GridMover</td><td>Moved</td><td>「動いた」（移動後の位置・方向）</td></tr></tbody></table></div></figure>



<p class="wp-block-paragraph">処理の流れをまとめると、次のようになります。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-plain"><code>[PlayerInput] 矢印キーを押す → MoveRequested
      ↓
[PlayerController] OnMoveRequested → GridMover.TryMove()
      ↓
[GridMover] MoveAttempted → 1マス移動 → Moved
      ↓
[PlayerController] OnMoveAttempted → PlayerDirectionSprite.Face()（画像を切り替え）

[PlayerInput] キーを離す → Released → PlayerDirectionSprite.ShowIdle()</code></pre></div>



<h4 class="wp-block-heading">キー長押しで連続移動する（repeatDelay・repeatInterval）</h4>



<p class="wp-block-paragraph">PlayerInputのUpdate()では、キーを押したときと、押し続けているときで処理を分けています。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-csharp" data-lang="C#"><code>// 有効なキーが変わった：即移動
if (currentIndex != previousIndex)
{
    repeatTimer = repeatDelay;
    MoveRequested?.Invoke(bindings[currentIndex].direction);
    return;
}

//同じキーを押し続ける
repeatTimer -= Time.deltaTime;
if (repeatTimer &lt;= 0f)
{
    repeatTimer = repeatInterval;
    MoveRequested?.Invoke(bindings[currentIndex].direction);
}
</code></pre></div>



<p class="wp-block-paragraph">キーを押した瞬間はすぐに1マス進み、タイマーにrepeatDelay（0.2秒）をセットします。そのまま押し続けると、タイマーが0になったところで次の1マスに進み、以降はrepeatInterval（0.1秒）ごとに進みます。</p>



<p class="wp-block-paragraph">パソコンでキーを押しっぱなしにしたとき、1文字目のあとに少し間が空いてから文字が連続で入力されるのと同じ仕組みです。最初に少し待つことで、<strong>「1マスだけ動きたかったのに2マス進んでしまった」という誤操作を防げます。</strong></p>



<p class="wp-block-paragraph">Time.deltaTime（前のフレームからの経過時間）を引いているため、フレームレートが変わっても同じ速さで進みます。<strong>歩く速さを変えたいときは、InspectorでRepeat Intervalの値を調整</strong>してください。値を小さくするほど速く歩きます。</p>



<h4 class="wp-block-heading">キー同時押しの優先度</h4>



<p class="wp-block-paragraph">2つの矢印キーを同時に押したときにどちらへ進むかは、heldKeysリストで決めています。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-csharp" data-lang="C#"><code>//リスト更新（離されたキーを外し、新しく押されたキーを末尾に追加）
heldKeys.RemoveAll(i =&gt; !Input.GetKey(bindings[i].key));
for (int i = 0; i &lt; bindings.Length; i++)
{
    if (Input.GetKeyDown(bindings[i].key) && !heldKeys.Contains(i))
        heldKeys.Add(i);
}</code></pre></div>



<ol class="wp-block-list">
<li>RemoveAllで、もう押されていないキーをリストから外す</li>



<li>GetKeyDownで新しく押されたキーを見つけ、リストの<strong>末尾</strong>に追加する</li>
</ol>



<p class="wp-block-paragraph">リストの末尾が「一番最後に押したキー」になり、CurrentIndexはこの末尾のキーを返します。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-csharp" data-lang="C#"><code>private int CurrentIndex =&gt; heldKeys.Count &gt; 0 ? heldKeys[heldKeys.Count - 1] : None;</code></pre></div>



<p class="wp-block-paragraph">例えば、→キーを押しながら↑キーを押すと↑方向へ進みます。そのあと↑キーだけを離すと、リストには→キーが残っているため、すぐに→方向へ戻って進みます。</p>



<p class="wp-block-paragraph">入力をif文で上から順に調べる書き方だと、「↑と→を同時に押すと、いつも↑が勝つ」「同時に押すと斜めに進む」といった動きになりがちです。押した順番を覚えておくことで、プレイヤーの操作に素直に反応する移動になります。</p>



<h2 id="rtoc-8"  class="wp-block-heading">実装</h2>



<p class="wp-block-paragraph">5つのスクリプトは、プレイヤーのオブジェクトと、画像を表示するオブジェクトにアタッチします。</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1917" height="967" src="https://alicia-ing.com/wp-content/uploads/2026/09/attach-2.webp" alt="" class="wp-image-8990" srcset="https://alicia-ing.com/wp-content/uploads/2026/09/attach-2.webp 1917w, https://alicia-ing.com/wp-content/uploads/2026/09/attach-2-300x151.webp 300w, https://alicia-ing.com/wp-content/uploads/2026/09/attach-2-767x387.webp 767w, https://alicia-ing.com/wp-content/uploads/2026/09/attach-2-1024x517.webp 1024w, https://alicia-ing.com/wp-content/uploads/2026/09/attach-2-1536x775.webp 1536w" sizes="(max-width: 1917px) 100vw, 1917px" /></figure>



<p class="wp-block-paragraph">各スクリプトは[RequireComponent]を使っていないため、必要なコンポーネントは自動で追加されません。SpriteRendererの追加と、PlayerControllerの参照の設定は、忘れずに手動で行ってください。</p>



<h2 id="rtoc-9"  class="wp-block-heading">まとめ</h2>



<p class="wp-block-paragraph">本記事では、Tilemapの上で2Dプレイヤーを矢印キーで1マスずつ動かす方法として、次の内容を解説しました。</p>



<ul class="wp-block-list">
<li>Input.GetKeyとGetKeyDownを組み合わせて、押した瞬間の移動と長押しの連続移動を作る</li>



<li>押したキーの順番をListで覚えて、同時押しでは後から押したキーを優先する</li>



<li>SpriteRenderer.spriteを差し替えて、進む方向に合わせて画像を切り替える</li>
</ul>



<p class="wp-block-paragraph">スクリプトを役割ごとに分けているため、ここから機能を足していくのも簡単です。次のステップとして、GridMoverに壁の判定を加えて「壁の方を向くだけで進めない」動きにしたり、Movedイベントを使ってマップの端で別のシーンへ切り替えたりすると、<strong>RPGのマップ移動らしく</strong>なります。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://alicia-ing.com/programming/unity/2dplayermove/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
