- 적이 죽으면 아이템이 랜덤 생성된다.
- 코인을 먹으면 점수 증가, 파워를 먹으면 플레이어 총알 업그레이드
- 붐아이템을 먹으면 UI에 붐아이템이 표시된다
- 키보드 B를 누르면 붐이펙트가 발생한다.
- 범위안의 적들이 모두 소멸된다.
-------------------------------
-적이 죽을때 아이템이 2개씩 생성되는 오류가 발생했음.
아이템
- 생성후 아래로 이동한다
-시간이 지나면 자동소멸된다
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Item : MonoBehaviour
{
public float speed=1f;
void Start()
{
Destroy(this.gameObject, 5f);
}
void Update()
{
transform.Translate(Vector3.down * speed * Time.deltaTime);
}
}
적
- hp가 0이되면 소멸하고 아이템을 랜덤으로 생성한다.
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
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;
public GameObject bulletA;
public GameObject bulletB;
public float maxSpawnDelay;
public float curSpawnDelay;
public int damage;
public int enemyscore;
public GameObject[] item;
public Player player;
public Boss boss;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
spriteRenderer = rb.GetComponent<SpriteRenderer>();
this.player = FindAnyObjectByType<Player>();
this.boss = FindAnyObjectByType<Boss>();
}
void Update()
{
if (player != null&& boss==null)
{
Move();
curSpawnDelay += Time.deltaTime;
if (curSpawnDelay > maxSpawnDelay)
{
Fire();
curSpawnDelay = 0;
}
}
//화면 밖으로 나가면 사라지게
if (transform.position.y < -4.4f)
{
Destroy(gameObject);
}
}
void Move()
{
//방향 * 속도 * 시간
Vector3 movement = Vector3.down * speed * Time.deltaTime;
transform.Translate(movement);
}
void Fire()
{
if (damage == 3)
{
GameObject bullet2 = Instantiate(bulletB, transform.position + Vector3.right * 0.25f, transform.rotation);
GameObject bullet3 = Instantiate(bulletB, transform.position + Vector3.left * 0.25f, transform.rotation);
}
else if (damage == 2)
{
}
else
{
GameObject bullet1 = Instantiate(bulletA, transform.position, transform.rotation);
}
}
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);
// 1개씩 생성
// 아이템 랜덤 생성
int temp = UnityEngine.Random.Range(0, 3);
Instantiate(item[temp], this.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 BoomEffect : MonoBehaviour
{
private Animator anim;
private Rigidbody2D rb;
public GameObject explosion;
private void Start()
{
anim = GetComponent<Animator>();
rb = GetComponent<Rigidbody2D>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "Enemy") //태그 설정
{
Destroy(collision.gameObject);
Instantiate(explosion, collision.transform.position, Quaternion.identity);
}
}
}
UIMain
- 붐 아이템을 획득하면 이미지가 하나씩 늘어남
- 아이템을 사용하면 이미지가 하나씩 줄어듬
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class UIMain : MonoBehaviour
{
public TMP_Text scoretext;
public Image[] lifeImages;
public GameObject gameover;
public GameObject restart;
public Button btnRestart;
public Player player;
private int currentLife; // 현재 라이프 개수
public bool isGameOver;
public GameObject[] boomImages;
public int currentBoom;
void Start()
{
currentLife = lifeImages.Length; // 초기 라이프 개수 설정 3
currentBoom = 0;
}
void Update()
{
this.scoretext.text = string.Format("{0:n0}", this.player.score) ;
}
// 라이프 감소 함수
public void DecreaseLife()
{
if (currentLife > 0) // 3
{
currentLife--; // 라이프 개수 감소 // 2,1,0
// Debug.LogFormat("lifeImg : {0}",currentLife);
lifeImages[currentLife].enabled = false; // 해당 라이프 이미지 비활성화
// 2초 후에 플레이어를 비활성화
}
}
public void OnPlayerDead()
{
//게임오버
isGameOver = true;
gameover.SetActive(true);
restart.SetActive(true);
btnRestart.onClick.AddListener(() =>
{
GameManager.instance.isGameOver = true;
});
}
public void IncreaseBoom()
{
if (currentBoom < 4) // 0
{
currentBoom++; // boomImg 개수 증가 1,2,3
Debug.LogFormat("BoomImg : {0}", currentBoom);
boomImages[currentBoom-1].SetActive(true); //0,1,2
}
}
public void DecreaseBoom()
{
if (currentBoom > 0) //0,1,2
{
currentBoom--; // boomImg 개수 감소
Debug.LogFormat("BoomImg : {0}", currentBoom);
boomImages[currentBoom].SetActive(false);// 해당 boom 이미지 비활성화
}
}
}
플레이어
- 키보드 B를 누르면 붐이펙트가 생성된다.
- 일정시간이 지나면 효과가 사라진다
using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using UnityEngine;
public class Player : MonoBehaviour
{
public float speed;
public Vector2 horizBoundary; //이동제한 범위 설정
public Vector2 vertBoundary;
public Sprite[] sprites;
SpriteRenderer spriteRenderer;
private Rigidbody2D rb;
Animator animator;
public GameObject bulletA;
public GameObject bulletB;
public int power;
public int boom;
public int hp;
public int maxhp;
public GameObject explosion;
public int life=3;
public int score=0;
public UIMain ui;
public GameObject boomEffect;
public float explosionRadius = 5f; // 폭발 반경
public float bombLifetime = 2f; // 폭탄 지속 시간
void Start()
{
rb = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
hp = maxhp;
}
void Update()
{
Move();
InCamera();
StartCoroutine( Shoot());
}
void ReturnSprite()
{
// spriteRenderer.sprite = sprites[0];
}
void Move()
{
float moveX = Input.GetAxisRaw("Horizontal");
float moveY = Input.GetAxisRaw("Vertical");
Vector3 dir = new Vector3(moveX, moveY, 0);
transform.Translate(dir.normalized * speed * Time.deltaTime);
//애니메이션 방향 전환
if (Input.GetButtonDown("Horizontal")|| Input.GetButtonDown("Vertical"))
{
animator.SetInteger("Input", (int)moveX);
}
}
void InCamera()//화면밖으로 나가지않게 하기
{
float clampX = Mathf.Clamp(rb.transform.position.x, horizBoundary.x, horizBoundary.y);
float clampY = Mathf.Clamp(rb.transform.position.y,vertBoundary.x, vertBoundary.y);
rb.transform.position = new Vector2(clampX, clampY);
}
IEnumerator Shoot() // 코루틴으로 변경
{
// 기본총알 발사
if (Input.GetKeyDown(KeyCode.Space))
{
//power아이템을 먹으면 총알 업그레이드
if (power >= 20)
{
GameObject bullet3 = Instantiate(bulletB, transform.position, transform.rotation);
GameObject bulletL = Instantiate(bulletA, transform.position + Vector3.left*0.25f, transform.rotation);
GameObject bulletR = Instantiate(bulletA, transform.position+Vector3.right*0.25f, transform.rotation);
}
else if(power >= 10)
{
GameObject bullet2 = Instantiate(bulletB, transform.position, transform.rotation);
}
else
{
GameObject bullet1 = Instantiate(bulletA, transform.position, transform.rotation);
}
}
if (Input.GetKeyDown(KeyCode.B))
{
if (ui.currentBoom > 0)
{
ui.DecreaseBoom();
LaunchBomb();
}
}
yield return new WaitForSeconds(0.2f);
}
void OnHit(int damage)
{
this.hp -= damage;
// Debug.LogFormat("player HP : {0}", hp);
if (hp <= 0)
{
ui.DecreaseLife();
this.life--;
this.hp += maxhp;
// Debug.LogFormat("player life : {0}", this.life);
// spriteRenderer.sprite = sprites[1];
Invoke("ReturnSprite", 0.1f); //Delay
}
if (this.life <= 0)
{
Destroy(gameObject); //게임오브젝트를 씬에서 제거
//폭발 프리팹 설정
Instantiate(explosion, transform.position, Quaternion.identity);
ui.OnPlayerDead();
}
}
private void LaunchBomb()
{
// 폭탄 생성
GameObject bomb = Instantiate(boomEffect, transform.position+Vector3.up*4, Quaternion.identity);
// 일정 시간 후에 폭탄 삭제
Destroy(bomb, bombLifetime);
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "EnemyBullet") //태그 설정
{
Destroy(collision.gameObject); //총알 소멸
EnemyBullet bullet = collision.gameObject.GetComponent<EnemyBullet>();
OnHit(bullet.damage);
}
if (collision.tag == "Enemy") //태그 설정
{
Enemy enemy = collision.gameObject.GetComponent<Enemy>();
OnHit(enemy.damage);
}
if (collision.tag == "Coin") //태그 설정
{
this.score += 100;
Destroy(collision.gameObject);
}
if (collision.tag == "Boom") //태그 설정
{
this.boom += 1;
Destroy(collision.gameObject);
if (this.boom >= 1)
{
if (ui.currentBoom <3)
{
ui.IncreaseBoom();
}
this.boom = 0;
}
Debug.LogFormat("boomg획득 {0}", boom);
}
if (collision.tag == "Power") //태그 설정
{
this.power += 1;
Destroy(collision.gameObject);
}
}
}
'게임프로젝트 > 슈팅게임' 카테고리의 다른 글
팀프로젝트 (1) App , Game Main스크립트 작성 (0) | 2024.03.21 |
---|---|
유니티 에셋을 이용한 오브젝트 풀링 (0) | 2024.03.20 |
ShootingSpace (4) UI만들기 (0) | 2024.03.16 |
ShootingSpace (3) 플레이어와 적, 적 총알과 충돌 (0) | 2024.03.12 |
ShootingSpace (2) 적 3종 랜덤 생성, 총알 충돌처리 (0) | 2024.03.09 |