KDT Unity 5주차 팀 프로젝트
2024-01-18 TIL
체크포인트 만들기
체크포인트를 위한 레이쏘기
Gizmo로 플레이어가 리스폰 될 지역을 만듭니다
해당 리스폰 지역에 플레이어가 접촉하게 되면 플레이어의 최근 리스폰 지점을 확인하고 같지 않으면 해당 리스폰 지역으로 플레이어의 최근 리스폰 지점을 업데이트 합니다.
레이는 Update에서 돌아가므로 해당 레이에 접촉시 같은 위치더라도 계속 업데이트 하므로 불필요한 업데이트를 제거하고자 같은 리스폰이면 한번만 실행되게 하였습니다.
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
public class PlayerRespawnGizmo : MonoBehaviour
{
public Color _color = Color.red;
public float _radius = 0.1f;
[SerializeField]float rayDistance = 10.0f; // 레이의 거리를 설정합니다.
[SerializeField] float rayPostion = 10.0f; // 레이의 범위를 설정합니다.
[SerializeField] LayerMask player;
private void OnDrawGizmos()
{
Gizmos.color = _color;
Gizmos.DrawSphere(transform.position, _radius);
}
private void Update()
{
Vector3 origin = new Vector3(transform.position.x - rayDistance / 2, transform.position.y, transform.position.z); // 레이의 시작점은 현재 객체의 위치입니다.
// 3개의 레이를 저장할 배열을 생성합니다.
Ray[] rays = new Ray[3];
// 각 레이를 생성하고 배열에 저장합니다.
for (int i = 0; i < rays.Length; i++)
{
// 레이의 시작점을 계산합니다. y축 방향으로 i만큼 이동시킵니다.
Vector3 rayOrigin = origin + new Vector3(0, -i* rayPostion, 0);
// 레이를 생성하고 배열에 저장합니다.
rays[i] = new Ray(rayOrigin, transform.right);
RaycastHit hit;
// 레이를 그립니다.
Debug.DrawRay(rays[i].origin, rays[i].direction * rayDistance, Color.red);
// 각 레이가 물체와 충돌하는지 확인합니다.
if (Physics.Raycast(rays[i], out hit, rayDistance, player))
{
PlayerCheckPoint checkPoint = hit.transform.GetComponent<PlayerCheckPoint>();
if (checkPoint.LastCheckPoint == transform.position) return;
checkPoint.CheckPoint(transform.position);
return;
}
}
}
}
플레이어에게 붙는 스크립트입니다.
deadZone이라는 레이어마스크를 선택할수 있게 하고 해당 레이어에 접촉시 최근 저장지점으로 사출됩니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class PlayerCheckPoint : MonoBehaviour
{
[SerializeField] Vector3 lastCheckPoint;
[SerializeField] LayerMask deadZone;
public Vector3 LastCheckPoint { get { return lastCheckPoint; } }
public void CheckPoint(Vector3 checkPoint)
{
lastCheckPoint = checkPoint;
Debug.Log(lastCheckPoint);
}
private void OnTriggerEnter(Collider other)
{
if ((deadZone.value & (1 << other.gameObject.layer)) != 0)
{
gameObject.transform.position = lastCheckPoint;
}
}
}
This post is licensed under CC BY 4.0 by the author.