コントロールキャラクターの歩行
1. CharacterController コンポーネントをキャラクターに追加し、CharacterController の SimpleMove を使用してキーボードを移動します。マウスで地面をクリックしてキャラクターを歩かせるには、主に自動パスファインディングの方法が使用されます。結合するとき、キーボード メソッドの else はキャラクターのアニメーションを停止するために無視されるため、地面をクリックしてもキャラクターには常にアニメーションがありません。ブール値 isMouse を追加すると、この小さな問題が解決されます。
using System;
using UnityEngine;
using UnityEngine.AI;
public class PlayerMovement : MonoBehaviour
{
private NavMeshAgent agent;
Camera cam;
private Animator animator;
private CharacterController characterController;
private float turnSpeed = 14f;
private float speed = 4.4f;
private bool isMouse;
void Start()
{
agent = gameObject.GetComponent<NavMeshAgent>();
cam = Camera.main;
animator = GetComponent<Animator>();
characterController = GetComponent<CharacterController>();
}
void Update()
{
MouseMove();
KeyBoardControl();
}
private void MouseMove()
{
if (Input.GetMouseButtonDown(0))
{
isMouse = true;
characterController.enabled = false;
animator.SetBool("isMoving", true);
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit hit))
{
if (hit.transform.CompareTag("Ground"))
{
agent.SetDestination(hit.point);
print(hit.point);
}
}
}
if (!agent.pathPending && agent.remainingDistance < 0.5f)
{
isMouse = false;
animator.SetBool("isMoving", false);
characterController.enabled = true;
}
}
private void KeyBoardControl()
{
if (isMouse)
{
return;
}
float h = Input.GetAxisRaw("Horizontal");
float v = Input.GetAxisRaw("Vertical");
characterController.SimpleMove(new Vector3(h, 0, v) * speed);
Vector3 input = (transform.right * h + transform.up * v).normalized;
if (h != 0 || v != 0)
{
Rotating(h, v);
}
if (input != Vector3.zero)
{
animator.SetBool("isMoving", true);
}
else
{
animator.SetBool("isMoving", false);
}
}
void Rotating(float h, float v)
{
Vector3 targetDir = new Vector3(h, 0, v);
Quaternion targetRotation = Quaternion.LookRotation(targetDir, Vector3.up);
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, turnSpeed * Time.deltaTime);
}
}
2. キャラクターの動きに合わせてカメラも動きます
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RotatingCamera : MonoBehaviour
{
private Transform player;
private bool isRotating = false;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player").transform;
}
void Update()
{
transform.position = player.position;
}
}