今回から、GoogleChromeブラウザで遊ぶことが出来る「恐竜ゲーム風味」のゲームをUnityで作成していきます。
はじめに
「GoogleChrome で遊べる恐竜ゲームって何?」って人は、GoogleChromeブラウザでアドレスに「chrome://dino/」と入力すると遊べます。

簡単に言うと、「恐竜(プレイヤー)が自動で走る」、「障害物をスペースキーでよける」ですね。細かくは色々とあるのですが、あくまでも「風味」で簡単に作ってみます。
今回やる事
パート1の今回はプレイヤーの移動とジャンプを実装していきます。
Unityのヴァージョンは2020.3.21f1。
あえて3Dで作成してみます。とはいえ、奥行きの移動は無いので3D風味ですかね。プロジェクト名は適当に「3DRunGame」としておきます。

製作開始
早速、作成していきます。
床とプレイヤーの作成
まずは床を作成していきます。
3Dオブジェクトから「キューブ」を追加。平面(Plane)にしようかと思ったのですが、なんとなくキューブの方が良い感じだったのでキューブで。

スケールを変更して、やや横長にしておきます。

次にプレイヤーを作成。3Dオブジェクトから「カプセル」を追加。

位置を変更しておきます。

カメラをプレイヤーの配下に移動、カメラの位置を適当に変更。

「シーン」と「ゲーム画面」が下記のような感じになるかと思います。
なんか、カイジの鉄骨渡りみたいな。

プレイヤーの移動
次にプレイヤーの移動を作成。
物体を移動させる方法は色々ありますが、今回はCharacterControllerを利用。(これくらいの移動だとリジッドボディの方が良い気もするけど、物は試しってことで)
プレイヤー(Capsule)に、コンポーネントを追加から「CharacterController」を追加。

Scriptsフォルダを作成、スクリプトを新規で作成。名前は「Player」にしておきます。

まずはスペースキーでジャンプするようにスクリプトを下記に変更。
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : MonoBehaviour { [SerializeField] float _jump = 15f; private CharacterController _characterController; private Vector3 _velocity; void Start() { _characterController = GetComponent<CharacterController>(); } void Update() { if (Input.GetKeyDown(KeyCode.Space)) { _velocity.y += _jump; } _characterController.Move(_velocity * Time.deltaTime); }
プレイヤーにスクリプトをくっつけます。

これで実行してスペースキーを押すと上に飛んでいくので「重力を追加して」、「2段ジャンプができないように(接地判定)」スクリプトを下記のように変更します。
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : MonoBehaviour { [SerializeField] float _jump = 15f; private CharacterController _characterController; private Vector3 _velocity; private Transform _transform; private float _gravity = -30f; private bool _isGround = true; void Start() { _characterController = GetComponent<CharacterController>(); _transform = GetComponent<Transform>(); } void Update() { //地面に接地 if (_transform.position.y <= 1.58f) { _velocity.y = 0; _isGround = true; } //ジャンプ中・落下中 else { _velocity.y += _gravity * Time.deltaTime; _isGround = false; } if (Input.GetKeyDown(KeyCode.Space) && _isGround) { _velocity.y += _jump; } _characterController.Move(_velocity * Time.deltaTime); } }
地面の接地判定はキャラクターの位置で判定しています。
キャラ位置の1.5と地面との幅0.08を加えた1.58fが0m地帯になるので、そこより下の時は接地と判定しています。「とりあえずは」です。

次に、自動でキャラが進むようにStart関数内を少し変更。
void Start() { _characterController = GetComponent<CharacterController>(); _transform = GetComponent<Transform>(); _velocity.x = 3; }
とりあえず、この状態で動かしてみると自動でプレイヤーが横に進み、ジャンプをすることが出来ます。
update関数で常に余分な動作をしている感があるので、結構微妙な感じの部分も多いですが・・・。とりあえず雰囲気はOK。