[Unity] 2D 모닥불 효과 만들기 및 플레이어 상호작용 구현(빛 세기, 데미지)
2D 모닥불 효과 만들기
혹시나 나중에 필요하거나 이 글을 읽는 누군가가 저처럼 필요할수도 있기에 세팅을 공유합니다.
Start Lifetime: 1~2
Start Speed: 1~1.5
Start Size: = 0.3
Start Rotation: -15 ~ 15
Start Color: 빨강(RGBA 255, 0, 0, 255, FF0000), 노랑(RGBA 255, 255, 0, 255, FFFF00)
Shape 설정
Shape: Cone
Angle: 30
Radius: 0.3
색상 알파 조절
좌측: 노랑(255, 255, 0) Alpha = 0
우측: 빨강(255, 0, 0) Alpha = 255
추가로
하이어라키 우클릭 → Effects → Particle System Force Field 추가하여 기존 파티클 시스템에 자식으로 넣습니다.
End Range = 1.5
Strength = 0.2
플레이어 위치에 따른 밝기 조절
public Light2D bonfireLight;
public Transform player;
public float maxRange = 10f; // 최대 거리
public float maxIntensity = 1.0f; // 최대 밝기
public float minIntensity = 0.5f; // 최소 밝기
void Update()
{
float distance = Vector3.Distance(player.position, transform.position);
if (distance <= maxRange)
{
float t = 1 - (distance / maxRange);
bonfireLight.intensity = Mathf.Lerp(minIntensity, maxIntensity, t);
}
else
{
bonfireLight.intensity = minIntensity;
}
}
플레이어와 모닥불 사이 거리를 계산해서,
최대 거리내에 들어올경우(플레이어가 다가올경우)
light2d의 intensity를 Mathf.Lerp 선형 보간 함수를 통해 조절
(t는 0과 1사이의 값을 선형보간한다, t가 0이면 minIntensity 1이면 maxIntensity반환)
bonfireLight에는 light2d가 있는 오브젝트를 할당해주고
player에는 이동할 캐릭터 오브젝트를 할당해준다.
플레이어가 모닥불에 다가오면 데미지 입히기
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Campfire : MonoBehaviour
{
public int damage;
public float damageRate; // 데미지 주는 주기 (초)
List<IDamageable> things = new List<IDamageable>();
void Start()
{
InvokeRepeating("DealDamage", 0, damageRate);
}
void DealDamage()
{
for (int i = 0; i < things.Count; i++)
{
things[i].TakePhysicsDamage(damage);
}
}
private void OnTriggerEnter(Collider other)
{
if (other.TryGetComponent(out IDamageable damageable))
{
things.Add(damageable);
}
}
private void OnTriggerExit(Collider other)
{
if (other.TryGetComponent(out IDamageable damageable))
{
things.Remove(damageable);
}
}
}
TryGetComponent를 통해 IDamageable 인터페이스를 상속받은 컴포넌트를 검사
플레이어가 모닥불에 가까이 다가가면 리스트에 추가, 멀어지면 리스트에서 제거
리스트에 있는 대상에게 TakePhysicsDamage를 호출해 데미지 적용
InvokeRepeating을 이용해 일정 주기로 데미지를 입히는 함수 호출