플레이어의 움직임 구현
Player - Add Component: Rigidbody 2D
Gravity Scale: 0 (1: 플레이어가 허공에서 떨어짐)
Collision Detection(충돌 감지): Continuous (Decrete: 물체 통과하는 경우 o)
Constraints
Freeze Rotation: Z (z축 회전 막아둠)
<aside> 💡 private vs public 변수 선언
public float speed;
player의 Inspector 창에서 변수 값 조정 가능
다른 스크립트에서 같은 이름 사용 시 실수로 사용될 위험 존재
private float speed;
Inspector 창에서 가려져서 변수 값 조정 불가능
[SerializeField] 사용해 Inspector 창에서도 조정 가능하도록 변경
</aside>
public class PlayerController : MonoBehaviour
{
private Rigidbody2D myRB;
[SerializeField]
private float speed; // 속도 변수 (Inspector창에서 5로 설정해놓음)
void Start()
{
// 캐릭터에 움직임요소 적용
myRB = GetComponent<Rigidbody2D>();
}
void Update()
{
// 유니티 내 이동요소 적용
myRB.velocity = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
}
}
*Project Settings 에서 확인 가능: Input Manager의 유니티 내 기본 세팅 (방향키, WASD키)
플레이어의 상하좌우 움직임이 가능해짐
플레이어의 움직임이 너무 느림
horizontal, vertical access가 기본 0~1 사이 값으로 세팅되어있기 때문에 플레이어의 Inspector 창에서 speed 변수의 값을 조정해도 소용없음 (현재 1로 설정되어있음)
스크립트 수정
public class PlayerController : MonoBehaviour
{
private Rigidbody2D myRB;
[SerializeField]
private float speed;
void Start()
{
myRB = GetComponent<Rigidbody2D>();
}
void Update()
{
// 기본 속도 설정값이 1인 Horizontal, Vertical >> speed 변수와 Time.deltaTime을 곱해줌
// 플레이어의 자연스러운 움직임을 위해 GetAxisRaw로 변경(더 빠릿해짐)
myRB.velocity = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")) * speed * Time.deltaTime;
}
}