control character walking
1. Add the CharacterController component to the character, and use the SimpleMove of the CharacterController to move the keyboard. Clicking the ground with the mouse to make the character walk mainly uses the way of automatic pathfinding. When combining, the else in the keyboard method is ignored to stop the animation of the character, so when the ground is clicked, the character always has no animation. Adding the Boolean value isMouse solves this small problem.
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. The camera moves with the movement of the characters
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;
}
}