筆者:織田 悠暉
今回は、ゲームエンジン「Unity」で2Dキャラクタを動かす方法を紹介します。具体的には、プレーヤのキャラクタと、地形の作成、左右の移動と、ジャンプ動作の実装、各動作に合わせてキャラクタの画像を変更する方法について解説します。とても手軽に実装できるので、皆さんもぜひチャレンジしてください。
図9 「Move」ファイル(「Move.cs」ファイル)に記述するコード
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.InputSystem; public class Move : MonoBehaviour { Rigidbody2D rigid2D; void Start() { rigid2D = GetComponent<Rigidbody2D>(); } void Update() { Vector2 right = new Vector2 (30f, 0); // 右向きの移動速度 Vector2 left = new Vector2 (-30f, 0); // 左向きの移動速度 // 右向きの移動 if (Keyboard.current.dKey.isPressed && (rigid2D.linearVelocity.magnitude < 7f)) { rigid2D.AddForce(right); } // 左向きの移動 if (Keyboard.current.aKey.isPressed && (rigid2D.linearVelocity.magnitude < 7f)) { rigid2D.AddForce(left); } } } |
図10 「Move」ファイル(「Move.cs」ファイル)に挿入するコード
1 2 3 4 5 6 7 8 |
void OnTriggerStay2D(Collider2D collision) { if (Keyboard.current.dKey.wasReleasedThisFrame || Keyboard.current.aKey.wasReleasedThisFrame) { rigid2D.linearVelocity = Vector2.zero; } } |
図11 「Jump」ファイル(「Jump.cs」ファイル)に記述するコード
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.InputSystem; public class Jump : MonoBehaviour { Rigidbody2D rigid2D; // ジャンプの速度 float speed = 350.0f; void Start() { rigid2D = GetComponent<Rigidbody2D>(); } void OnTriggerStay2D(Collider2D collision) { if(Keyboard.current.spaceKey.isPressed) { rigid2D.AddForce(Vector2.up * speed); } } } |
図13 「Anime」ファイル(「Anime.cs」ファイル)に記述するコード
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.InputSystem; public class Anime : MonoBehaviour { public Sprite[] character_anime; SpriteRenderer spriteRenderer; Rigidbody2D rigid2D; bool direction_right = true; void Start() { spriteRenderer = GetComponent<SpriteRenderer>(); rigid2D = GetComponent<Rigidbody2D>(); } private void Update() { if (rigid2D.linearVelocity.x > 0) direction_right = true; if (rigid2D.linearVelocity.x < 0) direction_right = false; } void OnTriggerStay2D(Collider2D collision) { if (direction_right) { if (rigid2D.linearVelocity.x == 0) spriteRenderer.sprite = character_anime[0]; else spriteRenderer.sprite = character_anime[2]; } else { if (rigid2D.linearVelocity.x == 0) spriteRenderer.sprite = character_anime[3]; else spriteRenderer.sprite = character_anime[5]; } } void OnTriggerExit2D(Collider2D collision) { if (direction_right) spriteRenderer.sprite = character_anime[1]; else spriteRenderer.sprite = character_anime[4]; } } |