2차시에서 만들던것을 이어서 해보자.
Player 오브젝트에 붙어있는 Rigidbody2D 컴포넌트가 있다.
안에는 여러가지 값들이 있는데 그중 Velocity는 오브젝트의 속도를 제어하는 변수이다.
우리는 이 Velocity값을 변경시켜서 플레이어를 움직이게 할것이다.
- 컴포넌트 가져오기
유니티 스크립트에서 컴포넌트를 가져오기 위해서는 GetComponent 함수를 써야한다.
먼저 Rigidbody2D를 담을 변수를 선언하자
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
Start 함수에 GetComponent 함수를 이용해서 변수에 Rigidbody2D를 담자.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
}
}
이제 우리는 Rigidbody2D에 접근해서 변수를 수정할 수 있게 됬다.
Update에다가 Rigidbody2D의 velocity를 수정하는 코드를 짜보겠다
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
rb.velocity = new Vector2(1, 0);
}
}
게임을 실행시켜보면 플레이어 오브젝트가 오른쪽으로 움직일 것이다. 움직이지 않을경우 코드에 오타가 있거나, Rigidbody2D 컴포넌트를 부착하지 않은것인지 확인해봐라.
- 키보드 입력 받아오기
움직이는 방법을 알았으니, 키보드 입력을 받아와보자.
키보드 입력은 Input에서 받아 올 수 있다.
Input.GetKey는 키보드에서 키가 눌리면 true, 아니면 false를 반환한다.
함수 안에는 KeyCode라는것이 들어가는데 어떤키가 눌렸는지 정하는 변수다.
KeyCode.W 같은 형식으로 쓴다. 자세한건 유니티 KeyCode 페이지에서 봐라.
if 로 확인해보자
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
if(Input.GetKey(KeyCode.W))
{
rb.velocity = new Vector2(1, 0);
}
}
}
실행했을때 w를 누르면 플레이어가 오른쪽으로 가는것을 확인 할 수 있다.