study/first_study/Assets/Scripts/PlayerSc/PlayerController.cs
jh04010421 aea5d47259 윤지호 | 유니티 연습
20226.01.22 수정 (대시구현)
2026-01-22 22:08:10 +09:00

139 lines
3.2 KiB
C#

using System.Collections;
using System.Collections.Generic;
using TreeEditor;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
Rigidbody2D rbody;
float axisH = 0.0f; // 입력
public float speed = 3.0f; // 이동 속도
public float jump = 7.0f; // 점프력
public LayerMask groundLayer; // 착지할 수 있는 레이어
bool goJump = false; // 점프 개시 플래그
bool isDead = false; // 사망 플래그
bool onGround = false; // 지면에 서 있는 플래그
Animator animator;
//public static string gameState = "playing"; // 게임 상태
// Start is called before the first frame update
void Start()
{
//Rigidbody2D 가져오기
rbody = GetComponent<Rigidbody2D>();
//Animator 가져오기
animator = GetComponent<Animator>();
//gameState = "playing"; // 게임중
}
// Update is called once per frame
void Update()
{
// 수평 방향의 입력 확인
axisH = Input.GetAxisRaw("Horizontal");
if (isDead)
{
return;
}
if (onGround)
{
animator.SetBool("jump", false);
}
else
{
animator.SetBool("jump", true);
}
// 방향 조절
if (axisH != 0) // 0이 아니면 (왼쪽이든 오른쪽이든 누르고 있으면)
{
animator.SetBool("Move", true);
float direction = axisH > 0 ? 1 : -1;
transform.localScale = new Vector2(direction, 1);
}
else
{
animator.SetBool("Move", false);
}
// 캐릭터 점프하기
if (Input.GetButtonDown("Jump"))
{
Jump();
}
}
private void FixedUpdate()
{
onGround = Physics2D.Linecast(transform.position,
transform.position - (transform.up * 0.1f),
groundLayer);
if (isDead)
{
return;
}
if (onGround || axisH != 0)
{
// 지면 위 or 속도가 0 아님
// 속도 갱신하기
rbody.linearVelocity = new Vector2(speed * axisH, rbody.linearVelocity.y);
}
if (onGround && goJump)
{
Debug.Log("점프!");
Vector2 jumpPw = new Vector2(0, jump);
rbody.AddForce(jumpPw, ForceMode2D.Impulse);
goJump = false;
}
}
public void Jump()
{
animator.SetBool("jump", true);
goJump = true;
Debug.Log(" 점프 버튼 눌림! ");
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Goal")
{
Goal();
}
else if (collision.gameObject.tag == "Dead")
{
GameOver();
}
}
public void Goal()
{
GameStop();
}
public void GameOver()
{
isDead = true;
GameStop();
}
void GameStop()
{
// Rigidbody2D 가져오기
Rigidbody2D rbody = GetComponent<Rigidbody2D>();
// 속도를 0으로 하여 강제 정지
rbody.linearVelocity = new Vector2 (0, 0);
}
}