1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public class CubeMove : MonoBehaviour { public float speed = 10f; void Update() { transform.position += Moving(); } public Vector3 Moving() { float h = Input.GetAxis("Horizontal"); float v = Input.GetAxis("Vertical"); Vector3 move = Vector3.zero; move.x += h * Time.deltaTime * speed; move.z += v * Time.deltaTime * speed; return move; } } | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public class CameraMove : MonoBehaviour { // GameObject cube; CubeMove cubeMove; void Start() { // cube = GameObject.Find("Cube"); // cubeMove = cube.GetComponent<CubeMove>(); cubeMove = GameObject.Find("Cube"). GetComponent<CubeMove>(); } void Update() { transform.position += cubeMove.Moving(); } } | cs |
- 코드 해석
Moving 함수에서 Horizontal, Vertical 입력 값을 받고, Vector3 move 값에 저장하고 리턴. 즉 입력값이자 이동할 방향 = move
transform.position (위치 정보)에 move 값을 더해 이동하도록 구현
CameraMove 스크립트에선 씬에 있는 Cube라는 오브젝트의 CubeMove 스크립트 정보를 가져와 저장하고, 해당 CubeMove의 moving 함수를 호출하며 Cube와 동일하게 "ransform.position +=" 연산
요약
1. CubeMove 스크립트에서 입력 값에 따라 움직일 방향을 가진 Vector3 값을 반환하는 함수를 가짐
2. CubeMove Update에서 transform.position 에 그 Vector3 값을 더해줌
3. CameraMove 에서도 똑같이 같은 값을 더해줌
(누구의 CubeMove인지 알기 위해 GameObject.Find("Cube").GetComponent<CubeMove>()로 가져와 변수로 저장)
- 이전 코드가 안됐던 이유
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public class CubeMove : MonoBehaviour { void Update() { transform.position += Moving(); } public Vector3 Moving() { float h = Input.GetAxis("Horizontal"); float v = Input.GetAxis("Vertical"); Vector3 move = transform.position; move.x += h * Time.deltaTime * 10; move.z += v * Time.deltaTime * 10; transform.position = move; } } | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public class CameraMove : MonoBehaviour { GameObject camove; void Start() { camove = GameObject.Find("Cube"); } void Update() { camove.GetComponent<CubeMove>().Moving(); } } | cs |
CubeMove 스크립트에선 "자신의" transform.position 을 수정하는 코드였음. 그러므로 CameraMove 에서 CubeMove의 moving을 호출해도 CubeMove를 가진 Cube의 transform.position만 바뀌게 된 것. 즉, Cube를 움직이게하는 스크립트를 실행하고 있었던 것