第三人称:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private CharacterController controller;
private Animator animator;
[SerializeField] float moveSpeed;
[SerializeField] float runSpeed;
[Header("运动速度太小,放大一定的倍数播放动画")]
[SerializeField] float moveSpeedMagnification;
[SerializeField] float runSpeedMagnification;
float _moveSpeed;
float _moveSpeedMagnification;
void Start()
{
controller = GetComponent<CharacterController>();
animator = GetComponentInChildren<Animator>();
}
void Update()
{
MovePlayer();
}
void MovePlayer()
{
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
if (Input.GetKey(KeyCode.LeftShift))
{
_moveSpeed = runSpeed;
_moveSpeedMagnification = runSpeedMagnification;
}
else
{
_moveSpeed = moveSpeed;
_moveSpeedMagnification = moveSpeedMagnification;
}
Vector3 dir = new Vector3(horizontal,0,vertical).normalized;
Vector3 velocity = _moveSpeed * Time.deltaTime * dir;
if (dir.magnitude >= 0.1f)
{
transform.rotation = Quaternion.LookRotation(dir);
controller.Move(velocity);
}
animator.SetFloat("Speed", velocity.magnitude * _moveSpeedMagnification);
}
}
第一人称:
void Update()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
Vector3 dir = new Vector3(h, 0, v).normalized;
Vector3 velocity = 2 * Time.deltaTime * dir;
transform.localEulerAngles += Vector3.up * h * 30f * Time.deltaTime;
transform.Translate(velocity);
if (Input.GetKey(KeyCode.Z))
{
transform.position -= Vector3.up * Time.deltaTime * 2;
}
if (Input.GetKey(KeyCode.X))
{
transform.position += Vector3.up * Time.deltaTime * 2;
}
}