study/first_study/Assets/Scripts/PlayerController2.cs
2026-01-21 21:37:37 +09:00

132 lines
3.3 KiB
C#

using System.Collections;
using System.Collections.Generic;
using TreeEditor;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerController2 : MonoBehaviour
{
[SerializeField] private Rigidbody2D rbody;
private Vector2 moveInput;
[SerializeField] private float speed = 3.0f; // 이동 속도
[SerializeField] private float dashspeed = 5.4f;
[SerializeField] private float jumpForce = 5.0f; // 점프력
private float axisH = 0.0f; // 좌우 입력 값 저장
bool isDash = false; // 대시 플래그
bool goJump = false; // 점프 개시 플래그
bool isDead = false; // 사망 플래그
bool onGround = false; // 지면에 서 있는 플래그
public LayerMask groundLayer; // 착지할 수 있는 레이어
private Animator animator;
// Start is called before the first frame update
void Start()
{
//Rigidbody2D 가져오기
rbody = GetComponent<Rigidbody2D>();
//Animator 가져오기
animator = GetComponent<Animator>();
}
void OnMove(InputValue value)
{
// Vector2 값 중 x축(좌우) 값만 가져옴
Vector2 inputVector = value.Get<Vector2>();
axisH = inputVector.x;
}
void OnDash(InputValue value)
{
isDash = value.isPressed;
animator.SetBool("Dash", isDash);
if (isDash) Debug.Log("대시 중...");
else Debug.Log("대시 중단");
}
public void OnJump(InputValue value)
{
// 버튼이 눌린 순간(isPressed)이고 지면 위라면 점프 예약
if (value.isPressed && onGround)
{
goJump = true;
animator.SetBool("jump", true);
Debug.Log(" 점프 버튼 눌림! ");
}
}
// Update is called once per frame
void Update()
{
if (isDead)
{
return;
}
animator.SetBool("jump", !onGround);
// 방향 조절
if (axisH != 0)
{
animator.SetBool("Move", true);
float direction = axisH > 0 ? 1 : -1;
transform.localScale = new Vector2(direction, 1);
}
else
{
animator.SetBool("Move", false);
animator.SetBool("Dash", false);
}
}
private void FixedUpdate()
{
onGround = Physics2D.Linecast(transform.position,
transform.position - (transform.up * 0.1f),
groundLayer);
if (isDead)
{
return;
}
float currentSpeed = (isDash && onGround) ? dashspeed : speed;
rbody.linearVelocity = new Vector2(axisH * currentSpeed, rbody.linearVelocity.y);
if (goJump)
{
Debug.Log("점프!");
rbody.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
goJump = false;
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Goal"))
{
GameStop();
}
else if (collision.CompareTag("Dead"))
{
GameOver();
}
}
public void GameStop()
{
rbody.linearVelocity = Vector2.zero;
}
public void GameOver()
{
isDead = true;
animator.SetBool("Move", false);
GameStop();
}
}