Unity FPS第一人称控制器

文章目录[x]
  1. 1:
    FPS移动
  2. 2:
    FPS视角旋转

FPS移动

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FPSRun : MonoBehaviour
{
public CharacterController controller;
//创建公共变量
public float speed = 12f;
public Transform groundCheck;
//检查用的球面半径
public float groundDistance = 0.4f;
public LayerMask groundMask;
public float jumpheight = 3f;
public float gravity = -9.81f;
Vector3 velocity;
bool isGrounded;
// Update is called once per frame
void Update()
{
//创建一个球面检测是否与在物体上
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if (isGrounded&& velocity.y<0)
{
velocity.y = -2f;
}
//获取
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");

//跳跃
if (isGrounded && Input.GetButtonDown("Jump"))
{
velocity.y = Mathf.Sqrt(jumpheight * -2f * gravity);
}
Vector3 move = transform.right * x + transform.forward * z;
//调用
controller.Move(move * speed * Time.deltaTime);

//赋值给y加速度
velocity.y += gravity * Time.deltaTime;
//调用
controller.Move(velocity * Time.deltaTime);
}
}

FPS视角旋转

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FPSlook : MonoBehaviour
{
//获取xyz轴
private Transform camerTransform;
//储存三维变量
private Vector3 camerRotation;
//创建共有的变量 灵敏度
public float MouseSensitvity;
//序列化
//[SerializeField]
//private Transform characterTransform;

void Start()
{
//初始化
camerTransform = transform;
//当游戏开始时隐藏鼠标
Cursor.lockState = CursorLockMode.Locked;

}
void Update()
{
//获取用户鼠标输入
var tmp_MouseX = Input.GetAxis("Mouse X");
var tmp_MouseY = Input.GetAxis("Mouse Y");

//存储XY轴
camerRotation.x -= tmp_MouseY * MouseSensitvity;
camerRotation.y += tmp_MouseX * MouseSensitvity;
//限制X轴旋转
camerRotation.x = Mathf.Clamp(camerRotation.x, -65f, 65f);

//
camerTransform.rotation = Quaternion.Euler(camerRotation.x, camerRotation.y,0f);
//camerRotation.y = Quaternion.Euler(0,camerRotation.,0);
}
}

记录一下!!!

点赞

发表评论

bupt_logo
Title - Artist
0:00