具体操作内容
人物脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterMove : MonoBehaviour
{
private Rigidbody rigid;//玩家刚体
public Transform mCamera;//相机组件
private Vector3 moveDir;//人物移动方向
private float currentVelocity = 1;//目前的转向速度(SmoothDampAngle函数的返还参数)
private float smoothTime = 0.1f;//完成平滑的时间(SmoothDampAngle函数的参数)
public float moveSpeed;//移动速度
public float rotateSpeed;//旋转速度
public float jPower;//跳跃力度
private float inputH;//水平移动参数
private float inputV;//垂直移动参数
private bool isMove;//是否移动
private bool isRun;//是否奔跑
private bool isGround;//是否在地面上
void Start()
{
rigid = GetComponent<Rigidbody>();
//animator = GetComponent<Animator>();
}
private void Update()
{
inputH = Input.GetAxis("Horizontal");//获取水平/垂直移动参数
inputV = Input.GetAxis("Vertical");
if (Input.GetKeyDown(KeyCode.Space) && isGround)
{
isGround = false;
rigid.AddForce(0, jPower, 0);//给刚体向上的力
}//更新跳跃动画
if (inputH != 0 || inputV != 0)
{
isMove = true;
transform.eulerAngles = Vector3.up * Mathf.SmoothDampAngle(transform.eulerAngles.y, (Mathf.Atan2(inputH, inputV) * Mathf.Rad2Deg + mCamera.eulerAngles.y), ref currentVelocity, smoothTime, rotateSpeed, Time.deltaTime);
}//改变人物朝向
else
{
isMove = false;
}//更新移动状态
if (Input.GetKey(KeyCode.LeftShift))
{
moveSpeed = 6;
isRun = true;
}//更新奔跑状态
else
{
moveSpeed = 3;
isRun = false;
}
moveDir = mCamera.TransformDirection(inputH, 0, inputV);
rigid.MovePosition(transform.position + new Vector3(moveDir.x, 0, moveDir.z) * moveSpeed * Time.fixedDeltaTime);//移动人物
}
private void OnCollisionEnter(Collision collision)
{
//需要给地面添加Tag标签 Ground
//当接触到地面时将isGround设置为True
if (!isGround)
{
if (collision.gameObject.CompareTag("Ground"))
{
isGround = true;
}
}//判断是否接地
}
}
摄像机脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour
{
public Transform body;//玩家人物组件
public float maxY = 40;//相机旋转上界限
public float minY = -10;//相机旋转下界限
public float xSpeed = 250;//相机纵向旋转速度
public float ySpeed = 125;//相机横向旋转速度
private float mouseX;//鼠标水平移动参数
private float mouseY;//鼠标垂直移动参数
void Update()
{
mouseX += Input.GetAxis("Mouse X") * xSpeed * Time.deltaTime;//更新鼠标水平/垂直移动参数
mouseY += Input.GetAxis("Mouse Y") * ySpeed * Time.deltaTime;
mouseY = clampAngle(mouseY);
transform.position = body.position;//相机跟随人物移动
transform.rotation = Quaternion.Euler(mouseY, mouseX, 0);//相机旋转
}
private float clampAngle(float angle)
{
if (angle < -360)
{
angle += 360;
}
if (angle > 360)
{
angle -= 360;
}
return Mathf.Clamp(angle, minY, maxY);
}//控制相机上下旋转角度
}