プレーヤーが方向転換できるようにする

方向転換の実装
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(CharacterController))]
[RequireComponent(typeof(AudioSource))]
public class PlayerController : MonoBehaviour
{
public float walkSpeed;
public float runSpeed;
private Vector3 movement;
private CharacterController characterController;
private AudioSource audioSource;
// ★追加(方向転換)
public GameObject FPSCamera;
private Vector3 moveDir = Vector3.zero;
private void Start()
{
characterController = GetComponent<CharacterController>();
audioSource = GetComponent<AudioSource>();
}
private void Update()
{
PlayerMove();
}
void PlayerMove()
{
float moveH = Input.GetAxis("Horizontal");
float moveV = Input.GetAxis("Vertical");
movement = new Vector3(moveH, 0, moveV);
// ★追加(方向転換)
// 『FPSカメラの向き』に『プレーヤーが進むべき方向』を合わせる。
Vector3 desiredMove = FPSCamera.transform.forward * movement.z + FPSCamera.transform.right * movement.x;
moveDir.x = desiredMove.x * 5f;
moveDir.z = desiredMove.z * 5f;
// ★改良(方向転換)
if (Input.GetKey(KeyCode.LeftShift))
{
// 「movement」を「moveDir」に変更する。
characterController.Move(moveDir * Time.deltaTime * runSpeed);
}
else
{
// 「movement」を「moveDir」に変更する。
characterController.Move(moveDir * Time.deltaTime * walkSpeed);
}
}
}



【2019版】X_Mission(基礎/全51回)
他のコースを見る
方向転換の実装
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(CharacterController))]
[RequireComponent(typeof(AudioSource))]
public class PlayerController : MonoBehaviour
{
public float walkSpeed;
public float runSpeed;
private Vector3 movement;
private CharacterController characterController;
private AudioSource audioSource;
// ★追加(方向転換)
public GameObject FPSCamera;
private Vector3 moveDir = Vector3.zero;
private void Start()
{
characterController = GetComponent<CharacterController>();
audioSource = GetComponent<AudioSource>();
}
private void Update()
{
PlayerMove();
}
void PlayerMove()
{
float moveH = Input.GetAxis("Horizontal");
float moveV = Input.GetAxis("Vertical");
movement = new Vector3(moveH, 0, moveV);
// ★追加(方向転換)
// 『FPSカメラの向き』に『プレーヤーが進むべき方向』を合わせる。
Vector3 desiredMove = FPSCamera.transform.forward * movement.z + FPSCamera.transform.right * movement.x;
moveDir.x = desiredMove.x * 5f;
moveDir.z = desiredMove.z * 5f;
// ★改良(方向転換)
if (Input.GetKey(KeyCode.LeftShift))
{
// 「movement」を「moveDir」に変更する。
characterController.Move(moveDir * Time.deltaTime * runSpeed);
}
else
{
// 「movement」を「moveDir」に変更する。
characterController.Move(moveDir * Time.deltaTime * walkSpeed);
}
}
}



プレーヤーが方向転換できるようにする