공부/Game Bootcamp

[멋쟁이사자처럼 부트캠프 TIL] 유니티 게임 개발 3기 : Curve, 몬스터 생성, 몬스터와 충돌 이벤트

Ail_ 2024. 12. 17. 15:55

 

curve로 애니메이션 제어 가능(활용도 무궁무진)

public AnimationCurve curve = AnimationCurve.Linear(0, 0, 1, 1)

        while (1.0f >= t / duration)
        {
            Vector3 newPosition = Vector3.Lerp(itemBeginPOS, 
                boxTransform.position, curve.Evaluate(t / duration));

 

아이템 스포너 도입

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

public class ItemSpanwer : MonoBehaviour
{
    public GameObject itemPrefab;

    public float minSpawnTime;
    public float maxSpawnTime;
    
    void Start()
    {
        StartCoroutine(SpawnItem());
    }

    IEnumerator SpawnItem()
    {
        GameObject item = Instantiate(itemPrefab, transform.position, Quaternion.identity);
        float nextRandomTime = Random.Range(minSpawnTime, maxSpawnTime);
        
        yield return new WaitForSeconds(nextRandomTime);
        
        StartCoroutine(SpawnItem());
    }
    
    void Update()
    {
        
    }
}

크게...생김

 

itemObject의 Scale을 줄여주자

델리게이트

  • 델리게이트는 **"메서드를 저장하고 호출하는 데이터 타입"**입니다.
  • 메서드를 동적으로 변경하거나 여러 메서드를 연결하여 실행할 수 있습니다.
  • 콜백, 이벤트 처리 등에서 매우 유용하게 사용됩니다.

 

// SpawnedItem.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpawnedItem : MonoBehaviour
{
    public Action OnDestroiedAction; // Action 델리게이트: 메서드를 저장하는 역할

	public void OnDestroy()
	{
    	OnDestroiedAction?.Invoke(); // 아이템이 삭제될 때 등록된 메서드를 실행
	}
}
// ItemSpanwer.cs

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

public class ItemSpanwer : MonoBehaviour
{
    public GameObject itemPrefab;

    public float minSpawnTime;
    public float maxSpawnTime;
    
    void Start()
    {
        SpawnItemCallback();
    }

    IEnumerator SpawnItem()
    {
        float nextRandomTime = Random.Range(minSpawnTime, maxSpawnTime);
        
        yield return new WaitForSeconds(nextRandomTime);
        
        StartCoroutine(SpawnItem());
    }

    public void SpawnItemCallback()
    {
        GameObject item = Instantiate(itemPrefab, transform.position, Quaternion.identity);
        
        // 익명함수, 델리게이트 하나
        item.GetComponent<SpawnedItem>().OnDestroiedAction += () =>
        {
            StartCoroutine(SpawnItem());
        };
    }
    
    void Update()
    {
        
    }
}

 

카메라에 보일 레이어 지정 : Culling Mask

 

인벤토리에 아이템 들어가게 만들기

 

몬스터 추가

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

public class Monster : MonoBehaviour
{
    // 몬스터의 스프라이트 렌더러, 애니메이터, 리지드바디2D 컴포넌트를 저장할 변수들
    private SpriteRenderer _spriteRenderer;
    private Animator _animator;
    private Rigidbody2D _rigidbody;

    // 몬스터의 이동 속도 (속도 조절 가능)
    public float Speed = 0.0f;
    
    // 이동을 반복할 횟수를 설정하는 변수 (스위치 카운트)
    public int switchCount = 0;
    
    // 이동 횟수를 추적하는 변수
    public int moveCount = 0;

    // 몬스터의 이동 방향을 저장할 변수 (x값만 사용)
    public Vector2 _direction;

    void Start()
    {
        _spriteRenderer = GetComponent<SpriteRenderer>();
        _animator = GetComponent<Animator>();
    }

    // FixedUpdate()는 물리적 연산을 다룰 때 사용됨 (주로 Rigidbody 관련 작업에 적합)
    void FixedUpdate()
    {  
        // 몬스터의 현재 위치를 이동 방향(_direction)과 속도(Speed)에 맞게 업데이트
        // _direction.x는 이동 방향을 나타내며, Speed는 이동 속도를 나타냄
        transform.position += new Vector3(_direction.x * Speed * Time.deltaTime, 0, 0);

        // 이동 횟수를 증가시킴
        moveCount++;

        // 이동 횟수가 설정한 switchCount에 도달했을 때
        if (moveCount >= switchCount)
        {
            // 이동 방향을 반대로 바꿈 (뒤로 돌아서 움직이게 함)
            _direction *= -1;

            // 몬스터 스프라이트를 뒤집어 이동 방향에 맞게 보여줌
            // _direction.x가 0보다 작으면 좌측을 보고, 그렇지 않으면 우측을 봄
            _spriteRenderer.flipX = _direction.x < 0;

            // 이동 횟수를 초기화하여 다시 카운팅을 시작함
            moveCount = 0;
        }
    }
}

 

Layer와 태그

Layer에는 overrides, 즉 Include, Exclude 등 기능이 있음 = 대분류로 사용 가능 ex. monster

Tag는 소분류 느낌, Layer안에서 한번 더 그룹화하는, unity string group ex. ice monster, fire monster 등

 

캐릭터가 몬스터에게 닿으면 밀려나도록 만들기

 

각 개체에 HitCollision 추가

// HitCollisionMonster.cs

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

public class HitCollisionMonster : MonoBehaviour
{
    void OnTriggerEnter2D(Collider2D other)
    {
        Debug.Log(other.gameObject.name);
        Rigidbody2D rb = other.GetComponent<hitCollision>().parentRigidbody;
        Debug.Log(rb.gameObject.name);
    
        Vector3 backPosition =  rb.transform.position - transform.position;
        backPosition.Normalize();
        backPosition.x *= 4;
        rb.AddForce(backPosition * 1800, ForceMode2D.Force);   
        Debug.Log(backPosition);
    }
}
// HitCollision.cs

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

public class hitCollision : MonoBehaviour
{
    [NonSerialized] public Rigidbody2D parentRigidbody;
    
    // Start is called before the first frame update
    void Start()
    {
        parentRigidbody = GetComponentInParent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

 

 

오늘은 오랜만에 할만했다ㅎ