控制人物行走
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;
}
}