Playerをジャンプさせる

ジャンプの実装
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float walkSpeed;
private float speed;
private Vector3 movement;
private CharacterController controller;
private int clickCount = 0;
public float runSpeed;
private Vector3 moveDir = Vector3.zero;
private float gravity = 3f;
// ★追加(ジャンプ)
public float jumpPower;
public AudioClip jumpSound;
private AudioSource audioS;
void Start()
{
// ★追加(ジャンプ)
audioS = GetComponent<AudioSource>();
controller = GetComponent<CharacterController>();
speed = walkSpeed;
}
void Update()
{
PlayerMove();
}
void PlayerMove()
{
float moveH = Input.GetAxis("Horizontal");
float moveV = Input.GetAxis("Vertical");
movement = new Vector3(moveH, 0, moveV);
Vector3 desiredMove = Camera.main.transform.forward * movement.z + Camera.main.transform.right * movement.x;
moveDir.x = desiredMove.x * 3f;
moveDir.z = desiredMove.z * 3f;
moveDir.y -= gravity * Time.deltaTime;
controller.Move(moveDir * Time.deltaTime * speed);
if (Input.GetKeyDown(KeyCode.W))
{
clickCount += 1;
Invoke("ResetCount", 0.3f);
}
if (Input.GetKeyUp(KeyCode.W))
{
speed = walkSpeed;
}
// ★追加(ジャンプ)
if (controller.isGrounded)
{
moveDir.y = 0;
if (Input.GetKeyDown(KeyCode.Space))
{
moveDir.y = jumpPower;
audioS.clip = jumpSound;
audioS.Play();
}
}
}
void ResetCount()
{
if (clickCount != 2)
{
clickCount = 0;
return;
}
else
{
clickCount = 0;
speed = runSpeed;
}
}
}


【2021版】X_Mission(全34回)
他のコースを見る
ジャンプの実装
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float walkSpeed;
private float speed;
private Vector3 movement;
private CharacterController controller;
private int clickCount = 0;
public float runSpeed;
private Vector3 moveDir = Vector3.zero;
private float gravity = 3f;
// ★追加(ジャンプ)
public float jumpPower;
public AudioClip jumpSound;
private AudioSource audioS;
void Start()
{
// ★追加(ジャンプ)
audioS = GetComponent<AudioSource>();
controller = GetComponent<CharacterController>();
speed = walkSpeed;
}
void Update()
{
PlayerMove();
}
void PlayerMove()
{
float moveH = Input.GetAxis("Horizontal");
float moveV = Input.GetAxis("Vertical");
movement = new Vector3(moveH, 0, moveV);
Vector3 desiredMove = Camera.main.transform.forward * movement.z + Camera.main.transform.right * movement.x;
moveDir.x = desiredMove.x * 3f;
moveDir.z = desiredMove.z * 3f;
moveDir.y -= gravity * Time.deltaTime;
controller.Move(moveDir * Time.deltaTime * speed);
if (Input.GetKeyDown(KeyCode.W))
{
clickCount += 1;
Invoke("ResetCount", 0.3f);
}
if (Input.GetKeyUp(KeyCode.W))
{
speed = walkSpeed;
}
// ★追加(ジャンプ)
if (controller.isGrounded)
{
moveDir.y = 0;
if (Input.GetKeyDown(KeyCode.Space))
{
moveDir.y = jumpPower;
audioS.clip = jumpSound;
audioS.Play();
}
}
}
void ResetCount()
{
if (clickCount != 2)
{
clickCount = 0;
return;
}
else
{
clickCount = 0;
speed = runSpeed;
}
}
}


Playerをジャンプさせる