KDT Unity 5주차 팀 프로젝트
2024-01-19 TIL
일정 거리를 두고 부모를 따라다니는 객체 만들기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// Animation Test Prototype
//잘 작동하지만 부모 오브젝트의 위치를 계속 따라감으로 최단거리로 가지 못한다.
public class FollowerTest : MonoBehaviour
{
public float speed = 1.0f;
public Vector3 followPos;
public int followDelay;
public Transform parent;
public Queue<Vector3> parentPos;
private Vector3 prevParentPos; // 추가: 부모 객체의 이전 위치를 저장할 변수
void Awake()
{
parentPos = new Queue<Vector3>();
prevParentPos = parent.position; // 초기값 설정
}
// Update is called once per frame
void FixedUpdate()
{
Watch();
Follow();
}
private void Watch()
{
if (!parentPos.Contains(parent.position))
{
parentPos.Enqueue(parent.position);
}
// 부모 객체가 멈췄을 때 Queue에서 모든 위치 반환
if (parent.position == prevParentPos)
{
while (parentPos.Count > 0)
{
followPos = parentPos.Dequeue();
}
followPos = parent.position;
}
// Queue에 일정 데이터 개수가 넘어가면 그때부터 반환
else if (parentPos.Count > followDelay)
{
followPos = parentPos.Dequeue();
}
prevParentPos = parent.position; // 이전 부모 위치 업데이트
}
private void Follow()
{
transform.position = Vector3.Lerp(transform.position, followPos, Time.deltaTime * speed);
}
}
This post is licensed under CC BY 4.0 by the author.