키보드로 객체 움직이기
1.객체 생성
FPS이나 RPG게임에서 흔히들 사용하는 방향키를 이용한 객체 이동과 WASD 키를 이용한 객체 이동을 해보겠습니다.
[GameObject] -> [3D Object] -> [Tree] 로 객체를 만듭니다.
새로운 스크립트 파일을 생성하고 이름을 정해준뒤 만든 객체에 주입시킵니다.
2.키보드 반응에 따른 이동 소스
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TreeContoller : MonoBehaviour
{
public float speed = 0.5f; //이동할 속도 변수 선언
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
// 입력된 키값을 확인하여 이동처리
if (Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W))
{
//Translate 함수를 이용하여 이동 (X,Y,Z)
this.transform.Translate(0, 0, speed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D))
{
this.transform.Translate(speed * Time.deltaTime, 0, 0);
}
if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S))
{
this.transform.Translate(0, 0, -speed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A))
{
this.transform.Translate(-speed * Time.deltaTime, 0, 0);
}
}
}
위 예제를 작성한뒤 게임을 실행해보면 키보드 버튼에 따라 객체가 이동하는것을 확인할 수 있습니다.