using UnityEngine;

public class HeroController : MonoBehaviour
{
    private Animator anim;
    private Rigidbody2D rBody2D;
    [SerializeField]
    private float jumpForce = 1f;
    [SerializeField]
    private float moveSpeed = 1f;
    [SerializeField]
    private float headHeight; // 머리 높이 변수 추가
    private bool isJump = false;

    void Start()
    {
        this.anim = this.gameObject.GetComponent<Animator>();
        this.rBody2D = this.GetComponent<Rigidbody2D>();
    }

    private float h;
    void Update()
    {
        this.h = Input.GetAxisRaw("Horizontal");

        if (Input.GetKeyDown(KeyCode.Space) && !this.isJump)
        {
            this.rBody2D.AddForce(Vector2.up * this.jumpForce, ForceMode2D.Impulse);
            this.isJump = true;
        }

        if (this.isJump)
        {
            if (this.rBody2D.velocity.y > 0)
            {
                this.anim.SetInteger("State", 2);
            }
            else if (this.rBody2D.velocity.y < 0)
            {
                this.anim.SetInteger("State", 3);
            }
        }

        if (h != 0)
        {
            if (!this.isJump)
                this.anim.SetInteger("State", 1);

            this.transform.localScale = new Vector3(h, 1, 1);
            this.transform.Translate(Vector3.right * h * moveSpeed * Time.deltaTime);
        }
        else
        {
            if (!this.isJump)
                this.anim.SetInteger("State", 0);
        }
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Ground" || collision.gameObject.layer == LayerMask.NameToLayer("CheckPoint"))
        {
            // 충돌 지점의 y 위치가 캐릭터의 머리 높이보다 높은지 확인
            foreach (ContactPoint2D contact in collision.contacts)
            {
                if (contact.point.y > transform.position.y + headHeight)
                {
                    return; // 머리 부분과의 충돌이므로 다른 로직을 실행하지 않음
                }
            }

            if (this.isJump)
            {
                this.isJump = false;

                Debug.LogFormat("h ===> {0}", this.h);

                if (this.h != 0)
                {
                    //run 
                    Debug.Log("Run!");
                    this.anim.SetInteger("State", 1);
                }
                else
                {
                    //idle 
                    Debug.Log("Idle");
                    this.anim.SetInteger("State", 0);
                }
            }
        }
    }
}

[+캐릭터 위의 땅 충돌시 점프 상태로 멈추는 오류]

캐릭터의 머리 높이(headHeight)를 구해서 머리높이 이상의 벽에 충돌시 다른 로직이 발생하지 않도록 조정했다.

 

반응형

+ Recent posts