目次
はじめに
Unityでジャンプを実装する場合にはいくつかの方法があります
その中でも、よく使われるのが、
です
CharacterControllerとRigidbodyは一つのオブジェクトに両方ともつけてしまうと、挙動がおかしくなってしまうので、
適宜使い分けましょう
CharacterControllerを使用したジャンプ
CharacterControllerをつける

プレイヤーを選択し、AddComponentをおします

検索欄に「cha」と入力し、CharacterControllerを選択します
※コライダー(当たり判定)がついていない場合はつけておきましょう
スクリプトの作成

Create → C#Scriptをおします

スクリプトの名前をJumpにします
入力するスクリプト
using System.Collections.Generic;
using System.Collections;
using UnityEngine;
public class Jump : MonoBehaviour
{
private CharacterController characterController;// CharacterControllerを使うための変数
private Vector3 moveDirection;// CharacterControllerを動かすための変数
public float JumpPower;// ジャンプ力
void Start()
{
characterController = GetComponent<CharacterController>();// characterControllerにCharacterControllerの値を代入する
}
void Update()
{
if (characterController.isGrounded)// もし地面についていたら、
{
if (Input.GetKeyDown(KeyCode.Space))// もし、スペースキーがおされたら、
{
moveDirection.y = JumpPower;// y座標をジャンプ力の分だけ動かす
}
}
moveDirection.y += Physics.gravity.y * Time.deltaTime; //常にy座標を重力の分だけ動かす(重力処理)
characterController.Move(moveDirection * Time.deltaTime); //CharacterControlloerをmoveDirectionの方向に動かす
}
}

入力したらプレイヤーにドラッグ&ドロップします

プレイヤーを選択し、JumpPowerに好きな数字を入力します
※8ぐらいがオススメです
テストプレイをしてみると

スペースキーをおしたらジャンプします
Rigidbodyを使用したジャンプ
Rigidbodyをつける

プレイヤーを選択し、AddComponentをおします

検索欄に「ri」と入力し、Rigidbodyを選択します
※2Dの場合は、Rigidbody2Dを選択します
スクリプトの作成

Create → C#Scriptをおします

スクリプトの名前をJumpと入力します
入力するスクリプト
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Jump : MonoBehaviour
{
private Rigidbody rb;// Rigidbodyを使うための変数
private bool Grounded;// 地面に着地しているか判定する変数
public float Jumppower;// ジャンプ力
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();// rbにRigidbodyの値を代入する
}
// Update is called once per frame
void Update()
{
if (Grounded == true)// もし、Groundedがtrueなら、
{
if (Input.GetKeyDown(KeyCode.Space))// もし、スペースキーがおされたなら、
{
Grounded = false;// Groundedをfalseにする
rb.AddForce(Vector3.up * Jumppower);// 上にJumpPower分力をかける
}
}
}
void OnCollisionEnter(Collision other)// 地面に触れた時の処理
{
if (other.gameObject.tag == "Ground")// もしGroundというタグがついたオブジェクトに触れたら、
{
Grounded = true;// Groundedをtrueにする
}
}
}

入力したらプレイヤーにドラッグ&ドロップします

プレイヤーを選択し、JumpPowerを入力します
※400ぐらいがオススメです
地面にタグをつける

地面を選択し、UnTaggedをおし、AddTagをおします

「+」をおし、タグの名前をGroundと入力し、Saveをおします

地面を選択し、UnTaggedをおし、Groundを選択します
テストプレイしてみると

スペースキーをおしたらジャンプします
コメント
コメント一覧 (1件)
[…] 今回はこちらを参考に準備しました […]