이렇게 설명하면서 코드 예시가 들어가면 이해가 되기는 하겠지만, 이런 설명은 다른 블로그 글이나 정리가 잘 된 사이트가 많다.
모던 자바스크립트 클래스 문서
그래서 클래스를 활용하는 라이브러리를 이용하기로 했다.
수많은 라이브러리 중에서 필자한테 익숙한 three.js와 유니티를 활용해 설명을 할 것이다.
브라우저에 3D를 표현하기 위해 도움을 주는 라이브러리다.
webgl을 javascript에서 쓰기 편하게 만든 것이라고 생각하면 된다.
three.js 공식 홈페이지
let scene = new THREE.Scene();
let camera = new THREE.PerspectiveCamera(
45, // fov
window.width/window.height, // aspect
1, // near
1000 // far
);
THREE라는 클래스에 해당하는 함수를 불러오는 방식이다.
class Scene extends Object3D {
constructor() {
super(); // 상속
this.isScene = true;
this.type = 'Scene';
this.background = null;
this.environment = null;
this.fog = null;
this.overrideMaterial = null;
this.autoUpdate = true;
if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
__THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
}
}
//...(중략)
}
Object3D를 상속받았기 때문에 super()가 들어갔다는 걸 확인할 수 있다.
class PerspectiveCamera extends Camera {
constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
super();
this.isPerspectiveCamera = true;
this.type = 'PerspectiveCamera';
this.fov = fov;
this.zoom = 1;
this.near = near;
this.far = far;
this.focus = 10;
this.aspect = aspect;
this.view = null;
this.filmGauge = 35;
this.filmOffset = 0;
this.updateProjectionMatrix();
}
// ...(중략)
}
이것도 상속받았기 때문에 super()가 들어가있다.
fov, aspect, near, far 값도 입력되지 않았을 경우에 기본값을 지정해줬다.
이를 보면 일반 함수를 만들 때와 동일하다고 보면 된다.
이 부분은 유니티를 활용해 더 이해하기 쉽도록 진행하려 한다.
public GameObject bulletPrefab;
public float spawnRateMin = 0.5f;
public float spawnRateMax = 3f;
위와 같이 public을 나열했을 경우, 외부에서 조작이 가능하다.
private Transform target;
private float spawnRate;
private float timeAfterSpawn;
// ... (중략)
target = FindObjectOfType<PlayerController>().transform;
spawnRate = Random.Range(spawnRateMin, spawnRateMax);
timeAfterSpawn += Time.deltaTime;
private으로 했을 경우,
위 코드와 같이 모두 Bullet Spawner에 있음에도 불구하고, public을 제외한 모든 게 외부에선 조작이 불가능하다.
그리고 private으로 분류된 모든 변수는 클래스 내부에서 모두 직접 선언해줬다는 것을 알 수 있다.
// GameManager.cs
public static GameManager instance;
public void OnPlayerDead() {
isGameover = true;
gameoverUI.SetActive(true);
}
// PlayerController.cs
GameManager.instance.OnPlayerDead();
static 선언을 했을 경우, 전역 변수 사용 가능하다.
protected 선언을 했을 경우, private과 같이 외부에서 접근이 불가능하다.
static과 비슷하지만 지역 변수 느낌이라고 생각하면 된다.
상속받은 extends가 붙은 클래스일 경우에만 사용이 가능하다.