前回の記事
UnityでFPSゲームを作る③RigidBodyとジャンプの実装
前回の記事で実装したジャンプの連続で飛べてしまうという問題点を直島しょう。
実装するアルゴリズム
床にtagをつけ床にPlayerのClliderが接触しているかつスペースキーが押されたときにジャンプするようにする。
①Groundタグを作成する。
PlayerのインスペクターからGroundタグを作成しアタッチします。
②スクリプトを変更する。
前回のPlayerJump.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 |
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerJump : MonoBehaviour { public GameObject Player; private Rigidbody PlayerRigid; public float Upspeed; // Use this for initialization void Start () { PlayerRigid = Player.GetComponent<Rigidbody>(); } // Update is called once per frame void Update () { } void OnCollisionStay(Collision col) { if (col.gameObject.tag == "Ground" && Input.GetKey(KeyCode.Space)) //Groundと接触している、かつスペースキーが押されたとき { PlayerRigid.AddForce(transform.up * 130); } } } |
地面となるオブジェクト(その上でジャンプを許可したいオブジェクト)にはGroundタグをアタッチしてください