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

ShootingSpace (3) 플레이어와 적, 적 총알과 충돌

by pudding81 2024. 3. 12.

 

 

적의 총알에 맞으면 플레이어의 HP 감소 

적과 충돌하면 플레이어의 HP 감소 

플레이어의  HP가 0이되면 폭발한다.

 

 

적의 총알 프리팹 만들기 

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

public class EnemyBullet : MonoBehaviour
{
    
    public float speed;
    public int damage;
    void Update()
    {
        // 아래로 이동하기
        transform.Translate(Vector3.down * speed * Time.deltaTime);

        //화면 밖으로 나가면 사라지게
        if (transform.position.y < -4.4f)
        {
            Destroy(gameObject);
        }



    }

}

 

 

적 프리팹 수정

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;




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

    }
    void Update()
    {
        Move();

        curSpawnDelay += Time.deltaTime;


        if (curSpawnDelay > maxSpawnDelay)
        {
            Fire();          
            curSpawnDelay = 0;

        }
       
       

    }


    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);
            
           

        }


    }

    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 System.Xml;
using UnityEngine;

public class Player : MonoBehaviour
{
    public float speed;
    public Vector2 horizBoundary; //이동제한 범위 설정
    public Vector2 vertBoundary;

    private Rigidbody2D rb;
    Animator animator;

    public GameObject bulletA;
    public GameObject bulletB;
    public float power;
    public int hp =10;
    public GameObject explosion;


    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        animator = GetComponent<Animator>();    

    }

    void Update()
    {
        Move();
        InCamera();
        StartCoroutine( Shoot());
    }

    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 >= 10)
            {
                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 >= 5)
            {
                GameObject bullet2 = Instantiate(bulletB, transform.position, transform.rotation);

            }

            else
            {
                GameObject bullet1 = Instantiate(bulletA, transform.position, transform.rotation);

            }


            

        }

        yield return new WaitForSeconds(0.2f);
       

    }

    void OnHit(int damage)
    {
        this.hp -= damage;
      

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



        }

        Debug.LogFormat("player HP : {0}", hp);
    }


// 충돌 설정 
    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);
        }




    }


   
 }