3D 게임을 만들려면 공간에서 오브젝트를 어디에 둘지, 어느 쪽으로 옮길지, 어디로 힘을 보낼지 등을 정해야 하므로 float형의 x, y, z 값 세 개를 씁니다. C#에는 이러한 값을 하나로 합쳐 다룰 수 있는 Vector3 클래스(정확히는 구조체라고 합니다.)가 준비되어 있죠. 반면 2D 게임용에는 float형의 x, y 값을 갖는 Vector2 클래스가 있습니다.
Vector3 클래스의 구조는 다음과 같습니다.
class Vector3 { public float x; public float y; public float z; // Vector용 멤버 메서드가 아래에 이어진다. }
이처럼 Vector3 클래스에는 x, y, z 멤버 변수가 있고, Vector2 클래스에는 x, y 멤버 변수가 있습니다. 둘 다 좌표나 벡터로 쓸 수 있죠.
Vector2 클래스의 멤버 변수에 숫자 더하기
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Test : MonoBehaviour { void Start() { Vector2 playerPos = new Vector2(3.0f, 4.0f); playerPos.x += 8.0f; playerPos.y += 5.0f; Debug.Log(playerPos); } }
Vector 클래스 끼리 뺄셈하기
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Test : MonoBehaviour { void Start() { Vector2 startPos = new Vector2(2.0f, 1.0f); Vector2 endPos = new Vector2(8.0f, 5.0f); Vector2 dir = endPos - startPos; Debug.Log(dir); float len = dir.magnitude; Debug.Log(len); } }
'game as a service' 카테고리의 다른 글
[서평] 초보자를 위한 유니티 입문 (2) | 2023.04.22 |
---|---|
Google I/O 2019 Codelab 중 Unity와 Firebase를 활용하는 실습 (0) | 2021.01.01 |
유니티 연습 4 : 클래스 (0) | 2020.12.27 |
유니티 연습 3 : 메서드(함수) (0) | 2020.12.27 |
유니티 연습 2 : 배열 (0) | 2020.12.27 |