


적 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);
}
}
'게임프로젝트 > 슈팅게임' 카테고리의 다른 글
유니티 에셋을 이용한 오브젝트 풀링 (0) | 2024.03.20 |
---|---|
ShootingSpace (5) 아이템 획득, 붐 이펙트 (0) | 2024.03.19 |
ShootingSpace (4) UI만들기 (0) | 2024.03.16 |
ShootingSpace (3) 플레이어와 적, 적 총알과 충돌 (0) | 2024.03.12 |
ShootingSpace (1) player 이동, 총알 3종 발사하기 (0) | 2024.03.09 |