Files
Knight_Hollow/Assets/Scripts/Player/PlayerMove.cs
Mingu Kim 5b48bad730 플랫폼별 입력 화장성을 위해 Inputs구조체 추가 및 InputControoller 추가
- 캐릭터 이동이 정상적으로 작동하지 않는 문제 수정
2025-08-30 21:06:16 +09:00

108 lines
3.2 KiB
C#

using System;
using UnityEngine;
using UnityEngine.PlayerLoop;
public struct Inputs
{
public bool Jump;
public Vector2 Move;
public bool Attack;
}
public class InputController
{
public static void UpdateInput(ref Inputs inputs)
{
inputs.Jump = Input.GetButtonDown("Jump");
inputs.Move.x = Input.GetAxisRaw("Horizontal");
inputs.Attack = Input.GetMouseButtonDown(0);
}
}
public class PlayerMove : MonoBehaviour
{
// 컴포넌트 프로퍼티
public Rigidbody2D RigidBody { get; private set; }
public SpriteRenderer SpriteRenderer { get; private set; }
public Animator Animator { get; private set; }
public float maxSpeed;
public float jumpPower;
private Inputs _inputs;
public Inputs Inputs => _inputs;
// 변수
[SerializeField]
public int hp = 5;
private StateMachine _stateMachine;
// 공격 콜라이더
public Collider2D attackCollider;
// 사용하는 컴포넌트들 초기화
void Awake()
{
// 중복 변수 제거하고 public 프로퍼티에 직접 할당
RigidBody = GetComponent<Rigidbody2D>();
SpriteRenderer = GetComponent<SpriteRenderer>();
Animator = GetComponent<Animator>();
// Null 체크 추가
if (RigidBody == null || SpriteRenderer == null || Animator == null)
{
Debug.LogError("PlayerMove 스크립트에는 동일한 GameObject에 Rigidbody2D, SpriteRenderer 및 Animator 구성 요소가 필요합니다.");
// 게임 오브젝트 비활성화 또는 스크립트 비활성화
enabled = false;
return;
}
// 캐릭터의 기본 방향을 오른쪽으로 설정
Vector3 initialScale = transform.localScale;
initialScale.x = -1f;
transform.localScale = initialScale;
_stateMachine = new StateMachine(State.IDLE, this);
// AttackArea 게임 오브젝트를 찾고 그 자식에서 Collider2D를 가져옵니다.
Transform attackAreaTransform = transform.Find("AttackArea");
if (attackAreaTransform != null)
{
attackCollider = attackAreaTransform.GetComponent<Collider2D>();
}
if (attackCollider == null)
{
Debug.LogError("AttackArea 자식 객체나 Collider2D 구성 요소를 찾을 수 없습니다!");
}
}
private void Update()
{
// 모든 입력값을 매 프레임 업데이트
InputController.UpdateInput(ref _inputs);
// 상태 머신 업데이트
_stateMachine.Update();
// 프레임이 끝난 후, 다음 프레임을 위해 "GetButtonDown"으로 받는 입력들은 리셋( Jump와 Attack )
_inputs.Jump = false;
_inputs.Attack = false;
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Enemy"))
{
// 중복 호출 제거, 피격 위치를 전달하는 메서드만 사용
_stateMachine.SetTransition(State.Damaged, collision.transform.position);
}
}
// 플레이어 오브젝트를 파괴하는 메서드
public void Die()
{
Destroy(gameObject);
}
}