86 lines
2.8 KiB
C#
86 lines
2.8 KiB
C#
|
|
using UnityEngine;
|
||
|
|
|
||
|
|
// PlayerController는 플레이어 캐릭터로서 Player 게임 오브젝트를 제어한다.
|
||
|
|
public class PlayerController : MonoBehaviour {
|
||
|
|
public AudioClip deathClip; // 사망시 재생할 오디오 클립
|
||
|
|
public float jumpForce = 700f; // 점프 힘
|
||
|
|
|
||
|
|
private int jumpCount = 0; // 누적 점프 횟수
|
||
|
|
private bool isGrounded = false; // 바닥에 닿았는지 나타냄
|
||
|
|
private bool isDead = false; // 사망 상태
|
||
|
|
|
||
|
|
private Rigidbody2D playerRigidbody; // 사용할 리지드바디 컴포넌트
|
||
|
|
private Animator animator; // 사용할 애니메이터 컴포넌트
|
||
|
|
private AudioSource playerAudio; // 사용할 오디오 소스 컴포넌트
|
||
|
|
|
||
|
|
private void Start() {
|
||
|
|
// 게임 오브젝트로부터 사용할 컴포넌트들을 가져와 변수에 할당
|
||
|
|
playerRigidbody = GetComponent<Rigidbody2D>();
|
||
|
|
animator = GetComponent<Animator>();
|
||
|
|
playerAudio = GetComponent<AudioSource>();
|
||
|
|
}
|
||
|
|
|
||
|
|
private void Update() {
|
||
|
|
if(isDead)
|
||
|
|
{
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
// 마우스 왼쪽 버튼을 눌렀으면 && 최대 점프 횟수(2)에 도달하지 않았다면
|
||
|
|
if(Input.GetMouseButtonDown(0) && jumpCount < 2)
|
||
|
|
{
|
||
|
|
jumpCount++;
|
||
|
|
|
||
|
|
// 점프 직전에 속도를 순간적으로 제로(0, 0)으로 변경
|
||
|
|
playerRigidbody.linearVelocity = Vector2.zero;
|
||
|
|
|
||
|
|
// 리지드바디에 위쪽으로 힘을 주기
|
||
|
|
playerRigidbody.AddForce(new Vector2(0, jumpForce));
|
||
|
|
playerAudio.Play();
|
||
|
|
}
|
||
|
|
else if(Input.GetMouseButtonUp(0) && playerRigidbody.linearVelocityY > 0)
|
||
|
|
{
|
||
|
|
// 마우스 왼쪽 버튼에서 손을 떼는 순간 && 속도의 y값이 양수라면(위로 상승중)
|
||
|
|
// 현재 속도를 절반으로 변경
|
||
|
|
playerRigidbody.linearVelocity = playerRigidbody.linearVelocity * 0.5f;
|
||
|
|
}
|
||
|
|
|
||
|
|
animator.SetBool("Grounded", isGrounded);
|
||
|
|
}
|
||
|
|
|
||
|
|
private void Die() {
|
||
|
|
// 애니메이터의 Die 트리거 파라미터를 셋
|
||
|
|
animator.SetTrigger("Die");
|
||
|
|
|
||
|
|
playerAudio.clip = deathClip;
|
||
|
|
|
||
|
|
playerAudio.Play();
|
||
|
|
|
||
|
|
playerRigidbody.linearVelocity = Vector2.zero;
|
||
|
|
|
||
|
|
isDead = true;
|
||
|
|
|
||
|
|
GameManager.instance.OnPlayerDead();
|
||
|
|
}
|
||
|
|
|
||
|
|
private void OnTriggerEnter2D(Collider2D other) {
|
||
|
|
if(other.tag == "Dead" && !isDead)
|
||
|
|
{
|
||
|
|
Die();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
private void OnCollisionEnter2D(Collision2D collision) {
|
||
|
|
// 어떤 콜라이더와 닿았으며, 충돌 표면이 위쪽을 보고 있으면
|
||
|
|
if(collision.contacts[0].normal.y > 0.7f)
|
||
|
|
{
|
||
|
|
isGrounded = true;
|
||
|
|
jumpCount = 0;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
private void OnCollisionExit2D(Collision2D collision) {
|
||
|
|
// 바닥에서 벗어났음을 감지하는 처리
|
||
|
|
isGrounded = false;
|
||
|
|
}
|
||
|
|
}
|