개발공부/유니티
[Unity] 유니티 오브젝트를 따라가는 카메라
정보를드립니다
2020. 1. 10. 20:20
반응형
안녕하세요
오브젝트를 따라가는 카메라를 만드는 코드를 공유하려고 합니다.
바닥(Plane)과 따라갈 오브젝트(Cube)를 생성합니다.
오브젝트(Cube)에 이동관련 스크립트를 추가합니다.
키보드로 이동이 가능하도록 추가합니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Mover : MonoBehaviour
{
float m_fSpeed = 5.0f;
void Update()
{
float fHorizontal = Input.GetAxis("Horizontal");
float fVertical = Input.GetAxis("Vertical");
transform.Translate(Vector3.right * Time.deltaTime * m_fSpeed * fHorizontal, Space.World);
transform.Translate(Vector3.forward * Time.deltaTime * m_fSpeed * fVertical, Space.World);
}
}
|
cs |
다음은 메인 카메라(Main Camera)에 오브젝트를 따라가는 스크립트를 추가합니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CFollowCamera : MonoBehaviour
{
public Transform target; // 따라다닐 타겟 오브젝트의 Transform
private Transform tr; // 카메라 자신의 Transform
void Start()
{
tr = GetComponent<Transform>();
}
void LateUpdate()
{
tr.position = new Vector3(target.position.x - 0.52f, tr.position.y, target.position.z - 6.56f);
tr.LookAt(target);
}
}
|
cs |
그리고 Target에 오브젝트(Cube)를 넣어줍니다.
실행을 해보면 오브젝트(Cube)를 따라서 카메라가 이동하게 됩니다.
위에서 바라보는게 더 자연스러울 것 같아서 카메라 위치를 변경해보겠습니다.
감사합니다.
반응형