角色运动系统
我们今天写角色的运动系统,也就是驱动角色运动的马达,经过了解和分析,我们能确定arpg游戏里的角色一般有移动和旋转的行为,那既然有移动和旋转的功能,肯定有移动速度和转向速度,Unity里面有自带的角色控制器,我们可以用这个作物理运动的碰撞检测等,那我们今天写一下这个类,我们这个类能给其他类提供移动速度和转向速度,还有移动功能和旋转功能,所以他们应该都用public。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace ARPG.Character
{
public class CharacterMotor : MonoBehaviour
{
/// <summary> 移动速度 </summary>
public float moveSpeed;
/// <summary> 转向速度 </summary>
public float rotateSpeed;
/// <summary> 角色控制器 </summary>
private CharacterController ch = null;
/// <summary> 角色动画系统 </summary>
private CharacterAnimation chAnimation = null;
public void Start()
{
ch = this.GetComponent<CharacterController>();
chAnimation = this.GetComponent<CharacterAnimation>();
}
/// <summary>
/// 移动方法,移动方法由于我们是用摇杆操控的
/// </summary>
/// <param name="horizontal">水平参数</param>
/// <param name="vertical">垂直参数</param>
public void Movement(float horizontal, float vertical)
{
if (horizontal != 0 || vertical != 0)
{
//用户一触碰摇杆就播放跑的动画
chAnimation.PlayAnimation("run");
//先转向
Rotating(horizontal, vertical);
//再移动 此处需要提个醒 游戏里角色的高度可以设个常量,即游戏里的一切环境建设
//也都围绕着常量来,避免后期出现bug,角色会悬空,穿墙等
var direct = new Vector3(transform.forward.x, -1, transform.forward.z);
ch.Move(direct * moveSpeed * Time.deltaTime);
}
}
/// <summary>
/// 转向功能,我们要先给角色一个方向,这个方向是由玩家用摇杆操作的得到的方向,
/// 然后让角色面朝那个方向
/// </summary>
/// <param name="horizontal"></param>
/// <param name="vertical"></param>
public void Rotating(float horizontal,float vertical)
{
//确定目标方向
Vector3 targetDiretion = new Vector3(horizontal, 0, vertical);
//转向目标
LookAtTarget(targetDiretion, this.transform, rotateSpeed);
}
/// <summary>
/// 面向目标方向
/// </summary>
/// <param name="targetDiretion">目标方向</param>
/// <param name="transform">需要转向的对象</param>
/// <param name="ratateSpeed">转向速度</param>
public void LookAtTarget(Vector3 targetDiretion, Transform transform, float ratateSpeed)
{
if (targetDiretion != Vector3.zero)
{
//确定目标角度
var targetRotation = Quaternion.LookRotation(targetDiretion, Vector3.up);
//从当前角度转向到目标角度
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, rotateSpeed);
}
}
}
}
以后可能会进行不定时的重构,因为开发是会越来越完善的,而不是一次就完善的。
