1.Unity场景
动画状态转化:
角色场景:
2.控制器
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript1 : MonoBehaviour
{
//characterController是一个组件,可以控制角色的移动
private CharacterController controller;
//animation是一个组件,可以控制角色的动画
private Animator animator;
// Start is called before the first frame update
void Start()
{
controller = GetComponent<CharacterController>();
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
//获取键盘的输入
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector3 dir = new Vector3(horizontal, 0, vertical);
//添加判断是否按下了键盘
if (dir != Vector3.zero)
{
transform.rotation = Quaternion.LookRotation(dir);
animator.SetBool("isRun", true);
transform.Translate(Vector3.forward * 2 * Time.deltaTime);
}
else
{
animator.SetBool("isRun", false);
}
}
}
3.摄像头
实现第三人称视角追随角色移动:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class camera : MonoBehaviour
{
public Transform target;
public float distance = 3.0f; // distance,与目标物体的距离
public float height = 3.0f; // height,与目标物体的高度差
public float damping = 2.0f; // damping,与目标物体的距离差
public bool smoothRotation = true;
public bool followBehind = true;
public float rotationDamping = 2.0f; // rotation,旋转速度
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Vector3 wantedPosition;
if (followBehind)
wantedPosition = target.TransformPoint(0, height, -distance);
else
wantedPosition = target.TransformPoint(0, height, distance);
transform.position = Vector3.Lerp(transform.position, wantedPosition, Time.deltaTime * damping);
if (smoothRotation)
{
Quaternion wantedRotation = Quaternion.LookRotation(target.position - transform.position, target.up);
transform.rotation = Quaternion.Slerp(transform.rotation, wantedRotation, Time.deltaTime * rotationDamping);
}
else transform.LookAt(target, target.up);
}
}