개발/Unity

유니티 3D 간보기 - 골드메탈 3D강좌:아이템 처리/수류탄 장착 구현

huiyu 2022. 2. 6. 18:58

아이템 편 마지막!

https://youtu.be/esGkgvm9eSg

수류탄 먹고, 캐릭터 주변 공전 시키기.

아래와 같이 아이템 변수를 추가.

    public GameObject[] grenades;
    public int hasGrenades;

    public int ammo;
    public int coin;
    public int health;

    public int maxAmmo;
    public int maxCoin;
    public int maxHealth;
    public int maxHasGrenades;

아이템 충돌시(OnTriggerEnter), 각 아이템 별 변수에 저장 처리.

    private void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Item")
        {
            Item item = other.GetComponent<Item>();
            switch (item.type)
            {
                case Item.Type.Ammo:
                    ammo += item.value;
                    if (ammo > maxAmmo)
                        ammo = maxAmmo;
                    break;

                case Item.Type.Coin:
                    coin += item.value;
                    if (coin > maxCoin)
                        coin = maxCoin;
                    break;

                case Item.Type.Heart:
                    health += item.value;
                    if (health > maxHealth)
                        health = maxHealth;
                    break;

                case Item.Type.Greenade:
                    grenades[hasGrenades].SetActive(true);
                    hasGrenades += item.value;
                    if (hasGrenades > maxHasGrenades)
                        hasGrenades = maxHasGrenades;
                    break;
            }
            Destroy(other.gameObject);
        }
    }

수류탄은 캐릭터가 먹은 후 캐릭터 주변을 돌 수 있게 만들기
 - GrenadeGroup을 만든 후, 사방에 수류탄을 붙여서 만들어준다.

  - 캐릭터 따라 공전할 수 있도록 스크립트 작성.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Orbit : MonoBehaviour
{
    public Transform target;
    public float orbitSpeed;
    Vector3 offset;

    void Start()
    {
        offset = transform.position - target.position;
    }

    void Update()
    {
        transform.position = target.position + offset;
        transform.RotateAround(target.position, Vector3.up, orbitSpeed * Time.deltaTime);

        offset = transform.position - target.position;
    }
}

Player에 생성한 Greades 배열에 생성한 4개의 수류탄을 각각 넣어준다.

수류탄을 하나씩 먹을때마다 얘네들을 활성화 시키면 된다. SetActive(true), 기본을 비활성화 상태로 만들기.

case Item.Type.Greenade:
    grenades[hasGrenades].SetActive(true);
    hasGrenades += item.value;
    if (hasGrenades > maxHasGrenades)
       hasGrenades = maxHasGrenades;
break;

수류탄 먹으며 이렇게 캐릭터 주변에 도는 객체 완성!! 역시 귀엽...

 

 

728x90
반응형