public class WalkMove : MonoBehaviour
{
public SteamVR_Input_Sources Hand;
[Header("vrHand与Hand是同一只手")]
public Transform vrHand;
public Transform player;
[Header("脚步声,跳跃声等的音频源")]
public AudioSource audioSource;
[Header("音效")]
[Tooltip("脚步的音效")] public AudioClip[] m_FootstepSounds;
[Tooltip("角色的移动速度")] public float walkSpeed = 5;
private float currentSpeed; //角色当前的速度
private float m_NextStep; //下一步的时间
private float m_StepCycle; //跳跃步骤周期
[Range(0f, 1f)] public float m_RunstepLenghten=0.7f; //步长加长
public float m_StepInterval=5; //步入间隔
public float angleSpeed = 2;
private CharacterController m_CharacterController;
private Vector3 desiredMove;
private bool m_IsWalking=false;
private void Start()
{
m_StepCycle = 0f;
m_NextStep = m_StepCycle / 2f;
currentSpeed = walkSpeed;
m_CharacterController = player.GetComponent<CharacterController>();
}
private void LateUpdate()
{
ControlMove();
}
/// <summary>
/// 控制人物的移动
/// </summary>
private void ControlMove()
{
if (Input.GetKeyDown(KeyCode.LeftShift))
{
currentSpeed = 7;
}
if (Input.GetKeyUp(KeyCode.LeftShift))
{
currentSpeed = walkSpeed;
}
}
private void FixedUpdate()
{
if (SteamVR_Actions._default.GrabPinch.GetState(Hand))
{
m_CharacterController.SimpleMove(new Vector3(vrHand.forward.x, 0, vrHand.forward.z) * 5);
ProgressStepCycle(currentSpeed);
}
}
/// <summary>
///
/// </summary>
/// <param name="speed"></param>
private void ProgressStepCycle(float speed)
{
//Vector3.sqrMagnitude 是指长度的平方,也就是Vector3.magnitude的平方
//比较向量的大小sqrMagnitude比magnitude的平方快,magnitude需要开平方
if (m_CharacterController.velocity.sqrMagnitude > 0)
{
m_StepCycle += (m_CharacterController.velocity.magnitude + (speed * (m_IsWalking ? 1f : m_RunstepLenghten))) *
Time.fixedDeltaTime;
}
if (!(m_StepCycle > m_NextStep))
{
return;
}
m_NextStep = m_StepCycle + m_StepInterval;
PlayFootStepAudio();
}
/// <summary>
/// 角色移动时的音效
/// </summary>
private void PlayFootStepAudio()
{
if (!m_CharacterController.isGrounded)
{
return;
}
int n = Random.Range(1, m_FootstepSounds.Length);
audioSource.clip = m_FootstepSounds[n];
audioSource.PlayOneShot(audioSource.clip);
m_FootstepSounds[n] = m_FootstepSounds[0];
m_FootstepSounds[0] = audioSource.clip;
}
}

image.gif
网友评论