반응형
Player가 상자에 닿으면 1초 후 Potion이 SetActive(true)가 되도록 설계하였다.
우선 체력 포션을 만들어줘야하는데 프로젝트 같이 하는 팀원의 코드를 참고하였다.
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.Diagnostics;
public class SJ_PotionUse : MonoBehaviour
{
public void HealHP() // HP를 3씩 회복, HP가 7 ~ 10 사이일 땐 최대 HP인 10으로 지정
{
GameObject playerObj = GameObject.Find("Player");
Playermove playerCon = playerObj.GetComponent<Playermove>();
if (playerCon.hp > 7 && playerCon.hp <= 10)
{
playerCon.hp = 10;
}
else playerCon.hp += 3;
}
private void OnTriggerEnter2D(Collider2D collision)
{
GameObject playerObj = GameObject.Find("Player");
Playermove playerCon = playerObj.GetComponent<Playermove>();
if (collision.tag == "Player") // 플레이어가 아이템에 닿으면 플레이어 체력 회복 후, 오브젝트 삭제
{
HealHP();
Debug.Log("HP 3 회복! (현재 체력 : " + playerCon.hp + " / 10)");
Destroy(this.gameObject);
}
}
}
체력이 10 이상이 되지 않게 조건문을 설정하여 잘 만들었다.
포션을 먹으면 사라지게 하기 위해 Destroy도 꼭 넣은 모습
다음은 상자를 알아봐야하는데 상자에게 닿으면 상자가 열리는 모션도 있어야하고 상자와 플레이어가 충돌하는 직후에 바로 포션이 뜨면 포션이 보이지도 않고 플레이어가 먹는 것 처럼 나온다. 그래서 딜레이를 주고 나오게 하였다.
using Cainos.PixelArtPlatformer_VillageProps;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UIElements;
public class GoldBox : MonoBehaviour
{
Rigidbody2D rb;
public GameObject Potion;
private float PotionDelay = 1.0f;
void Start()
{
rb = GetComponent<Rigidbody2D>();
Potion.SetActive(false);
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag.Equals("Player"))
{
BoxAnimation();
Invoke("Spawn",PotionDelay);
}
}
public void Spawn()
{
if (Potion != null) Potion.SetActive(true);
}
public void BoxAnimation()
{
Chest Chest = rb.GetComponent<Chest>();
Chest.Open();
}
}
우선 힐링 포션을 포션박스의 하위로 넣어줬다.
하위로 넣은 이유는 힐링 포션의 위치가 바로 포션박스 위치에 뜨게 하기 편하게 하기 위해서다.
그 다음 힐링 포션이 처음에는 보이면 안되기 때문에 Potion.SetActive(false); << 이 구문을 Start에 넣었다.
그 후 플레이어가 상자에 닿으면 상자가 열리는 애니메이션이 작동하고 포션이 1초 후에 SetActive(true)가 된다.
Spawn 함수에 != null 의 조건을 추가한 이유는 맵에 더 이상 포션이 없을 때 없는 오브젝트를 자꾸 참고할려고 해서 Null 레퍼런스 오류가 자꾸 떴다. 그래서 조건에 추가했다.
Shout out to 경일
반응형
'Unity' 카테고리의 다른 글
Unity) 반복되는 화살 트랩 (0) | 2023.09.18 |
---|---|
Unity) 범위(영역) 안에 들어오면 떨어지는 트랩 (0) | 2023.09.18 |