90 lines
2.2 KiB
C#
90 lines
2.2 KiB
C#
using System.Collections;
|
||
using System.Collections.Generic;
|
||
using UnityEngine;
|
||
using UnityEngine.AI;
|
||
|
||
public class KeyController : BaseController
|
||
{
|
||
/// <summary>
|
||
/// 控制对象的Transform
|
||
/// 若为空则控制当前脚本所在对象
|
||
/// </summary>
|
||
[Tooltip("控制对象的Transform,默认为当前对象")]
|
||
public Transform tran;
|
||
/// <summary>
|
||
/// 移动速度(米/秒)
|
||
/// </summary>
|
||
[Tooltip("移动速度(米/秒)")]
|
||
public float moveSpeed = 5;
|
||
/// <summary>
|
||
/// 旋转速度(角度/秒)
|
||
/// </summary>
|
||
[Tooltip("旋转速度(角度/秒)")]
|
||
public float rotateSpeed = 10;
|
||
/// <summary>
|
||
/// 移动时自动调整视角
|
||
/// </summary>
|
||
public bool AutoResetView = true;
|
||
|
||
void Start()
|
||
{
|
||
if (tran == null)
|
||
tran = transform;
|
||
}
|
||
|
||
float h, v;
|
||
|
||
void Update()
|
||
{
|
||
// Debug.Log(IsKeyOnControl);
|
||
if (CanControl)
|
||
{
|
||
if (Input.GetKey(KeyCode.Q))
|
||
{
|
||
tran.Rotate(Vector3.down * rotateSpeed * Time.deltaTime); // 左旋转
|
||
}
|
||
if (Input.GetKey(KeyCode.E))
|
||
{
|
||
tran.Rotate(Vector3.up * rotateSpeed * Time.deltaTime); // 右旋转
|
||
}
|
||
|
||
h = Input.GetAxis("Horizontal"); // 获取水平偏移量
|
||
v = Input.GetAxis("Vertical"); // 获取垂直偏移量
|
||
|
||
if (h != 0 || v != 0)
|
||
{
|
||
ControllWithKey(h, v);
|
||
}
|
||
else
|
||
{
|
||
IsKeyOnControl = false;
|
||
}
|
||
}
|
||
}
|
||
|
||
Vector3 tmp;
|
||
/// <summary>
|
||
/// 使用键盘控制对象
|
||
/// </summary>
|
||
/// <param name="h">水平偏移量</param>
|
||
/// <param name="v">垂直偏移量</param>
|
||
void ControllWithKey(float h, float v)
|
||
{
|
||
IsKeyOnControl = true;
|
||
|
||
//tran.position += tran.forward * moveSpeed * Time.deltaTime * v; // 移动
|
||
//tran.Rotate(Vector3.up * rotateSpeed * Time.deltaTime * h); // 旋转
|
||
|
||
tmp.x = h;
|
||
tmp.z = v;
|
||
if (Input.GetKey(KeyCode.LeftShift))
|
||
{
|
||
tran.Translate(tmp * moveSpeed * Time.deltaTime * 4f);
|
||
}
|
||
else
|
||
{
|
||
tran.Translate(tmp * moveSpeed * Time.deltaTime);
|
||
}
|
||
}
|
||
}
|