一、玩家旋转
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
*文件描述:
*创始人:
*创建时间:
*修改时间:
*版本:1.0
*/
public enum PlayerState//枚举
{
Idle,
Walk,
Run,
Shot
}
public class Player : MonoBehaviour
{
public float speed;
CharacterController cc;
Animation an;
void Start()
{
cc = GetComponent<CharacterController>();//获取角色控制器组件
an = GetComponent<Animation>();//获取动画组件
}
void PlayAnimation(PlayerState ps) {
switch (ps)
{
case PlayerState.Idle:
an.Play("Idle");//播放动画
break;
case PlayerState.Walk:
an.Play("Walk");
break;
case PlayerState.Run:
an.Play("Run");
break;
case PlayerState.Shot:
an.Play("Shoot");
break;
default:
break;
}
}
void Update()
{
float h = Input.GetAxis("Horizontal") * Time.deltaTime * speed;
float v = Input.GetAxis("Vertical") * Time.deltaTime * speed;
if (Mathf.Abs(h) > 0 || Mathf.Abs(v) > 0)
{
cc.SimpleMove(new Vector3(h, 0, v));//SimpleMove()自带刚体、受重力
transform.rotation = Quaternion.LookRotation(new Vector3(h, 0, v),Vector3.up);//控制玩家旋转,创建具有指定的向前和向上方向的旋转
PlayAnimation(PlayerState.Walk);
// an.Play("Walk");
}
else
{
// an.Play("Idle");
PlayAnimation(PlayerState.Idle);//播放站立动画
}
}
}
二、相机跟随玩家移动
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
*文件描述:
*创始人:
*创建时间:
*修改时间:
*版本:1.0
*/
public class FollowPlayer : MonoBehaviour {
Transform player;//玩家
Vector3 pos;//向量差
void Start () {
player = GameObject.FindWithTag(“Player”).transform;//找到玩家组件
pos = transform.position - player.position;//相机与玩家的向量差
}
void Update () {
transform.position = pos + player.position;//向量差+玩家移动的距离
}
}