본문 바로가기
게임프로젝트/슈팅게임

ShootingSpace (2) 적 3종 랜덤 생성, 총알 충돌처리

by pudding81 2024. 3. 9.

 

 
적 3종 프리팹으로 설정 
스프라이트 2종 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Scripting.APIUpdating;

public class Enemy : MonoBehaviour
{
    public float speed;

    public int hp;
    public Sprite[] sprites;
    SpriteRenderer spriteRenderer;

    Rigidbody2D rb;

    public GameObject explosion;

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        spriteRenderer = rb.GetComponent<SpriteRenderer>();

    }
    void Update()
    {
        Move();
    }


    void Move()
    {
        //방향 * 속도 * 시간 
        Vector3 movement = Vector3.down * speed * Time.deltaTime;
        transform.Translate(movement);

    }

    void OnHit(int damage)
    {
        this.hp-=damage;
        spriteRenderer.sprite = sprites[1];
        Invoke("ReturnSprite", 0.1f); //Delay

        if(hp<=0)
        {
            Destroy(gameObject);   //게임오브젝트를 씬에서 제거 
             //폭발 프리팹 설정
            Instantiate(explosion, transform.position, Quaternion.identity);
            
           

        }


    }

    void ReturnSprite()
    {
        spriteRenderer.sprite = sprites[0];
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag == "Bullet") //태그 설정 
        {
            Destroy(collision.gameObject); //총알 소멸
            PlayerBullet bullet = collision.gameObject.GetComponent<PlayerBullet>();

            OnHit(bullet.damage);
        }

    }



}

 
폭발효과 

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

public class Explosion : MonoBehaviour
{
    
   
    private void Awake()
    {
        Destroy(gameObject, 0.6f); // 생성뒤 없어지게
    }

   
}

 
적 3종 랜덤 생성하기 

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;

public class GameManager : MonoBehaviour
{

    public GameObject[] enemys;
    private Vector3 spawnPoints;  // 생성 위치

    public float maxSpawnDelay; // 생성 간격
    public float curSpawnDelay;  // 현재 시간

   void Update()
    {
        curSpawnDelay += Time.deltaTime;


        if(curSpawnDelay > maxSpawnDelay)
        {
            SpawnEnemy();
            maxSpawnDelay = Random.Range(2f,6f);  // 생성 간격 랜덤으로
            curSpawnDelay = 0;

        }
    }


    void SpawnEnemy()
    {
        int ranEnemy = Random.Range(0, 3);  // 에너미 종류 랜덤으로
        float randX = Random.Range(-2.2f, 2.2f);  // x축 랜덤 
        
        spawnPoints = new Vector3(randX, 6f, 0);  // 생성 위치
        Instantiate(enemys[ranEnemy], spawnPoints, Quaternion.identity);

    }




}