Unity3D
Unity) [유니티 3D] CharacterController를 통한 이동, 중력 적용
HSH12345
2023. 6. 27. 06:02
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private CharacterController controller;
private Vector3 playerVelocity;
private bool isGrounded;
private float playerSpeed = 2.0f;
private float jumpHeight = 1.0f;
private float gravityValue = -20.0f;
private float groundDistance = 0.2f;
private LayerMask groundMask;
private Transform transGroundCheckPoint;
private void Start()
{
this.controller = this.gameObject.GetComponent<CharacterController>();
// 캐릭터의 중심에서 레이를 발사합니다.
this.transGroundCheckPoint = this.transform;
// 각각의 layer 이름으로 LayerMask를 받아온 뒤 OR 연산을 통해 합칩니다.
this.groundMask = (1 << 6) | (1 << 7);
}
private void Update()
{
// Raycasting을 이용한 grounded 판별
this.isGrounded = Physics.Raycast(transGroundCheckPoint.position, Vector3.down, groundDistance, groundMask);
if (this.isGrounded && this.playerVelocity.y < 0)
{
this.playerVelocity.y = 0f;
}
Vector3 moveDir = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDir = moveDir * this.playerSpeed * Time.deltaTime;
// 플레이어의 이동 방향에 맞도록 회전합니다.
if (moveDir != Vector3.zero)
{
this.gameObject.transform.forward = moveDir;
}
// 제곱근을 사용하여 점프의 높이를 조절합니다.
if (Input.GetButtonDown("Jump") && this.isGrounded)
{
this.playerVelocity.y = Mathf.Sqrt(this.jumpHeight * -2.0f * this.gravityValue);
}
// 시간을 사용하여 중력 가속도를 구현합니다.
this.playerVelocity.y += this.gravityValue * Time.deltaTime;
// 이동
controller.Move(moveDir);
// 점프
controller.Move(this.playerVelocity * Time.deltaTime);
}
}
CharacterController 컴포넌트의 isGrounded 값이 정확하지 않아 레이캐스트를 사용하여 직접 선언한 isGrounded 값을 제어 하였고 해당 값을 통해 y방향으로 -값 만큼 이동하게 하여 중력을 구현하였습니다.