[Unity FPS Tutorial 1] First Person Shooter in UNITY
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : LivingEntity
{
[SerializeField]
private CameraController cameraController;
private PlayerMovement playerMovement;
void Awake()
{
playerMovement = GetComponent<PlayerMovement>();
}
void Update()
{
float x = Input.GetAxisRaw("Horizontal");
float y = Input.GetAxisRaw("Vertical");
playerMovement.MoveTo(new Vector3(x, 0, y));
if (Input.GetKeyDown(KeyCode.Space))
{
playerMovement.Jump();
}
if (Input.GetKeyDown(KeyCode.LeftShift))
{
playerMovement.speed = 70f;
}
float mouseX = Input.GetAxis("Mouse X"); // 마우스 좌/우 움직임
float mouseY = Input.GetAxis("Mouse Y"); // 마우스 위/아래 움직임
cameraController.RotateTo(mouseX, mouseY);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[HideInInspector]
public float speed = 30f;
private float jumpForce = 3f;
private float gravity = -9.8f;
private Vector3 moveDirection;
[SerializeField]
private Transform cameraTransform;
private CharacterController characterController;
private void Awake()
{
characterController = GetComponent<CharacterController>();
}
void Update()
{
//공중이라면 중력 적용
if(!characterController.isGrounded)
moveDirection.y += gravity * Time.deltaTime;
characterController.Move(moveDirection * speed * Time.deltaTime);
transform.rotation = cameraTransform.rotation;
}
public void MoveTo(Vector3 direction)
{
Vector3 movedis = cameraTransform.rotation * direction;
moveDirection = new Vector3(movedis.x, moveDirection.y, movedis.z);
}
public void Jump()
{
if (characterController.isGrounded)
moveDirection.y = jumpForce;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour
{
private float rotateSpeedX = 3f;
private float rotateSpeedY = 5f;
//x축 회전 각도 제한
private float limitMinX = -25f;
private float limitMaxX = 50f;
private float euerAngleX;
private float euerAngleY;
public void RotateTo(float mouseX, float mouseY)
{
//마우스 좌/우는 카메라 y축
//마우스 상/하는 카메라 x축
euerAngleY += mouseX * rotateSpeedX;
euerAngleX -= mouseY * rotateSpeedY;
//X축 각도 제한
euerAngleX = ClampAngle(euerAngleX, limitMinX, limitMaxX);
transform.rotation = Quaternion.Euler(euerAngleX, euerAngleY, 0);
}
private float ClampAngle(float angle, float min, float max)
{
if (angle < -360)
angle += 360;
if (angle > 360)
angle -= 360;
return Mathf.Clamp(angle, min, max);
}
}
