실행 이미지

 

using System.Collections;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public AudioClip deathClip; // 사망시 재생할 오디오 클립

    private bool isGrounded = false; // 바닥에 닿았는지 나타냄
    private bool isDead = false; // 사망 상태
    private bool isJumping = false; // 점프 중인지 나타냄

    public AnimationCurve UpJumpCurve; // 올라갈 때의 점프 곡선
    public AnimationCurve DownJumpCurve; // 내려올 때의 점프 곡선

    public int jumpCount = 0;

    public float jumpSpeedScale = 20f;

    public float jumpDuration = 0.3f; // 점프 지속 시간

    private Animator animator; // 사용할 애니메이터 컴포넌트
    private Rigidbody2D rb;

    private Coroutine currentJumpRoutine = null; // 현재 진행 중인 점프 코루틴의 참조

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        animator = GetComponent<Animator>();
        StartCoroutine("StartZeroGravityScale");
    }

    private void Update()
    {
        if (isDead) return;

        if (Input.GetMouseButtonUp(1) && jumpCount < 2) // 마우스 우클릭 감지
        {
            if (currentJumpRoutine != null)
            {
                animator.Play("Jump", 0, 0.0f); // 이중 점프 시, Jump 애니메이션 재시작
                StopCoroutine(currentJumpRoutine); // 진행 중인 점프 코루틴 중단
            }
            isJumping = true;
            jumpCount++;
            currentJumpRoutine = StartCoroutine(Jump()); // 새로운 점프 코루틴 시작
        }

        animator.SetBool("Grounded", isGrounded);
    }

    IEnumerator Jump()
    {
        float timer = 0;
        while (timer < jumpDuration)
        {
            float height = UpJumpCurve.Evaluate(timer / jumpDuration) * jumpSpeedScale;
            rb.velocity = new Vector2(rb.velocity.x, height);
            timer += Time.deltaTime;
            yield return null;
        }

        timer = 0;
        while (timer < jumpDuration && !isGrounded)
        {
            float height = DownJumpCurve.Evaluate(timer / jumpDuration) * jumpSpeedScale;
            rb.velocity = new Vector2(rb.velocity.x, -height);
            timer += Time.deltaTime;
            yield return null;
        }

        isJumping = false; // 점프 완료
    }



    private void Die()
    {
        animator.SetTrigger("Die");
        isDead = true;
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("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;
    }

    IEnumerator StartZeroGravityScale()
    {
        while (true)
        {
            if(isGrounded)
            {
                rb.gravityScale = 0;
            }
            yield return null;
        }
    }
}

PlayerController.cs

 

Player Controller 설정

반응형

+ Recent posts