[Unity 2D] Fly Bird 플레이어 따라 Camera 이동 구현
Bird가 움직이는 것처럼 구현하는 방법은 두 가지가 있다.
1. 배경 전체와 그라운드 등 플레이어를 제외한 나머지 배경들이 움직이는 것
2. 플레이어가 움직이는 것
1번 방법을 사용하면 비효율적이고, 배경화면이 많이 움직이지 않는 것이 좋기 때문에
2번 방법으로 Bird 를 앞으로(오른쪽으로) 이동하도록 구현해보겠다.
// Move 구현
[SerializeField] float moveSpeed = 5;
이동하기 위해선 이동할 방향과 이동 속도가 필요하다. (어디로 얼마나 이동할 건지)
그래서 이동 속도를 선언 후 초기화했다.
void MoveBird()
{
transform.Translate(Vector3.right * moveSpeed * Time.deltaTime, Space.World);
}
Unity 에서는 Translate 라는 메서드를 사용해서 오브젝트를 움직일 수 있다.
transform.Translate(이동방향 * 이동속도(어디까지 이동할 건지) * Time.deltaTime, Space World);
transform.Translate(Vector3.right * moveSpeed * Time.deltaTime, Space.World);
transform.Translate를 사용해서 오른쪽으로 (Vector3.right) moveSpeed만큼 (+5) 이동을 구현했다.
Time.deltaTime 을 같이 곱하여 프레임 당 계속 이동할 수 있도록 해준다.
Time.deltaTime 이란 한 프레임이 진행될 때 걸리는 시간을 뜻한다!
여기서 Space.World 는 기본적으로 기준이 되는 글로벌 좌표라고 생각하면 쉽다.
Space.World를 입력하지 않으면 자동적으로 Space.Self 가 적용되는데,
Space.Self는 자신이 수동적으로 정하는 (자신을 축으로 이동하는) 로컬 좌표이다.
사라져버렸지만... 앞으로 (right방향) 나아가는 Bird를 볼 수 있다.
이제 이 사라져버린 Bird 따라 Camera가 같이 이동하는 것을 구현해보자.
꽤 간단하다.
일단 Main Camera 에 넣을 스크립트를 만든다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour
{
// Main Camera가 Player를 따라 갈 속도
public float cameraSpeed = 5.0f;
// Player 지정하기
public Transform player;
void Update()
{
FollowPlayer();
}
void FollowPlayer()
{
transform.position = new Vector3(player.position.x, transform.position.y, transform.position.z);
}
}
Bird는 오른쪽으로만 이동하도록 구현했고,
어차피 위 아래로는 배경화면 안에서만 움직일 거기 때문에
카메라 화면 역시 position.x 좌표만 같이 따라 이동하면 된다.
메인 카메라에 스크립트를 넣으면 이렇게 인스펙터 창에서 관리할 수 있는 창이 새로 추가된다.
Player를 하이라키 창에서 드래그해서 넣어주면 된다.
그럼 이렇게 Bird를 따라가는 (x축만 따라가는) 카메라를 확인할 수 있다.
★
사실 내가 원래 작성했던 요절복통 오류 코드..
transform.position = player.transform.position;
이렇게 되면 플레이어 위치가 카메라 위치 (플레이어 = 카메라) 그 자체가 되기 때문에..
아무것도 보이지 않는다...^^
어떻게 알았냐구요? 나도 알고 싶지 않았다.
전체 코드
↓
Player.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
Rigidbody2D rb;
// Jump 구현
[SerializeField] float Speed = 5;
private bool keyJump = false;
// Rotate 구현
private Vector3 birdRotation;
[SerializeField] private float upRotate = 5f;
[SerializeField] private float downRotate = -5f;
// Move 구현
[SerializeField] float moveSpeed = 5f;
void Start()
{
// RigidBody2D 컴포넌트를 rb라는 변수를 통해 가져온다
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
InputBird();
RotateBird();
MoveBird();
}
private void FixedUpdate()
{
// 입력받은 Jump값이 true라면
if(keyJump == true)
{
// JumpBird메서드 받기
JumpBird();
// 그리고 다시 keyJump값은 false로 만들어준다.
keyJump = false;
}
}
void JumpBird()
{
// RigidBody2D의 Velocity는 Speed만큼 올라간다
rb.velocity = Vector3.up * Speed;
}
void RotateBird()
{
// Rotate값을 저장할 변수를 초기화했다
float degree = 0;
// 점프해서 올라갔을 때 +30도까지 회전한다
if(rb.velocity.y > 0)
{
degree = upRotate;
}
// 점프 후 내려갈 때 -90도까지 회전한다
else if(rb.velocity.y < 0)
{
degree = downRotate;
}
// birdRotation은 transform 이기 때문에 오일러 값으로 변환해 적용시켜준다
birdRotation = new Vector3(0,0,Mathf.Clamp((birdRotation.z + degree), -90, 30));
transform.eulerAngles = birdRotation;
}
void MoveBird()
{
transform.Translate(Vector3.right * moveSpeed * Time.deltaTime, Space.World);
}
void InputBird()
{
// Jump를 입력받는 메서드를 따로 생성했다.
// 스페이스바 혹은 마우스 좌버튼을 눌렀을 때
keyJump |= Input.GetKeyDown(KeyCode.Space);
keyJump |= Input.GetMouseButtonDown(0);
}
}
CameraController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour
{
// Main Camera가 Player를 따라 갈 속도
public float cameraSpeed = 5.0f;
// Player 지정하기
public Transform player;
void Update()
{
FollowPlayer();
}
void FollowPlayer()
{
transform.position = new Vector3(player.position.x, transform.position.y, transform.position.z);
}
}