using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
// 좌우이동 && 점프(velocity만 사용)
// 리지드바디2D형 변수선언
Rigidbody2D rb;
[HideInInspector]
public float speed = 5; // 좌우이동시 이동 속도
public float jumpPower = 8; // 점프력
float axisH; // 좌우이동 여부
// public 처럼 에디터에서 편집 가능, 하지만 외부스크립트에서는 접근불가(private)
[SerializeField] Transform tr; // 트랜스폼 컴포넌트 변수 선언
[SerializeField] float radius; // 반지름
[SerializeField] LayerMask isLayer; // 레이어마스크형 변수선언
bool isGround; // 레이어에 발밑이 닿았는지 여부
void Start()
{
// 리지드바디2D 컴포넌트 가져오기
rb = GetComponent<Rigidbody2D>();
// 충돌후 회전금지
rb.constraints = RigidbodyConstraints2D.FreezeRotation;
}
void Update()
{
// 좌우이동 감지
axisH = Input.GetAxisRaw("Horizontal"); // +1, -1, 0 세값중 하나
// 점프여부
isGround = Physics2D.OverlapCircle(tr.position, radius, isLayer); // true or false
if(isGround && Input.GetKeyDown("space"))
{
// 점프하기
rb.velocity = Vector2.up * jumpPower;
}
else if(isGround==false && Input.GetKeyDown("space"))
{
rb.velocity = Vector2.zero; // (0, 0)
}
}
void FixedUpdate()
{
// 좌우이동하기
rb.velocity = new Vector2(axisH * speed, rb.velocity.y);
// 좌우반전하기
if(axisH != 0) // +1 또는 -1이면
{
transform.localScale = new Vector2(axisH, 1);
}
}
}