先看效果:
(键鼠):
人物会随着指针转动,WASD控制人物移动。
鼠标
键盘就是去除掉键鼠的看向鼠标指针,改成看向最后方向
代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.EventSystems;
public enum EControlType
{
KeyBrd,
Mouse,
KeyMouse
}
public class PlayerController : MonoBehaviour
{
Animator animator;
NavMeshAgent agent;
public float speed = 5.0f;
public AudioClip clipFoot;
EControlType ControlType;
bool isKeyMouse;
void Start()
{
animator = GetComponent<Animator>();
agent = GetComponent<NavMeshAgent>();
agent.speed = speed;
}
void Update()
{
//按键
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
Vector3 dir = new Vector3(h, 0, v);
dir = Camera.main.transform.TransformDirection(dir);
dir.y = 0;
if (dir.magnitude > 0.1f)
{
ControlType = EControlType.KeyBrd;
agent.isStopped = true;
}
transform.Translate(dir * speed * Time.deltaTime, Space.World);
//网格导航寻路
transform.LookAt(dir + transform.position);
if (EventSystem.current.IsPointerOverGameObject())
{
return;
}
if (agent && Input.GetMouseButtonDown(1))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 1 << 6))
{
agent.destination = hit.point;
ControlType = EControlType.Mouse;
agent.isStopped = false;
}
}
//鼠标加键盘
if (agent)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
// 第三个参数:距离,第四个:碰撞器
if (Physics.Raycast(ray, out hit, 100f, 1 << 6))
{
if (Input.GetKeyDown(KeyCode.Space))
{
isKeyMouse = !isKeyMouse;
}
if (isKeyMouse)
{
ControlType = EControlType.KeyMouse;
transform.LookAt(hit.point);
agent.isStopped = false;
}
}
}
//二 动画和位移 切换方式
switch (ControlType)
{
case EControlType.KeyBrd:
transform.Translate(dir * speed * Time.deltaTime, Space.World);
animator.SetFloat("Speed", dir.magnitude);
transform.LookAt(transform.position + dir);
break;
case EControlType.Mouse:
float curSpeed = agent.velocity.magnitude / speed;
print("curSpeed= " + curSpeed);
animator.SetFloat("Speed", curSpeed);
break;
case EControlType.KeyMouse:
transform.Translate(dir * speed * Time.deltaTime, Space.World);
animator.SetFloat("Speed", dir.magnitude);
break;
}
}
void playFootSound()
{
AudioSource.PlayClipAtPoint(clipFoot, transform.position);
}
public void normalAttack(int index)
{
animator.SetInteger("NormalAttack", index);
}
}