[학원 Unity]/[게임 클라이언트 프로그래밍]

스페이스슈팅 코드

롤링페이퍼 2024. 8. 30. 00:39

1.ShooterController

using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class ShooterController : MonoBehaviour
{
    public Animator animator;   // 애니메이터
    public Rigidbody2D rb2D;    // 물리계산

    public float moveSpeed = 1f;    // 속도
    public GameObject playerBulletprefab;   // 총알
    public GameObject Boomfab;   // 폭탄

    // Update is called once per frame
    void Update()
    {
        ShooterMove();
        Bullet();
        Boom();
    }

    public void ShooterMove()
    {
        float h = Input.GetAxisRaw("Horizontal");   // 가로
        float v = Input.GetAxisRaw("Vertical");     // 세로

        Vector3 dir = new Vector3(h, v, 0);   // 방향

        // dir * this.moveSpeed * Time.deltaTime // 방향 * 속도 * 시간 = 위치
        Vector3 movement = dir.normalized * this.moveSpeed * Time.deltaTime;

        // 대각선을 위해
        this.transform.Translate(movement);

        //this.animator.SetInteger("State", (int)h);

        // 좌, 우
        if (h == 0)
        {
            this.rb2D.velocity = new Vector3(h*1, 0, 0);
            this.animator.SetInteger("State", 0);
        }
        else if (h == 1)
        {
            this.rb2D.velocity = new Vector3(h * 1, 0, 0);
            this.animator.SetInteger("State", 2);

        }
        else if (h == -1)
        {
            this.rb2D.velocity = new Vector3(h * 1, 0, 0);
            this.animator.SetInteger("State", 1);
        }

        // 상 하
        //if (v == 0)
        //{
        //    this.rb2D.velocity = new Vector3(0, v * 1, 0);
        //}
        //else if (v == 1)
        //{
        //    this.rb2D.velocity = new Vector3(0, v * 1, 0);

        //}
        //else if (v == -1)
        //{
        //    this.rb2D.velocity = new Vector3(0, v * 1, 0);
        //}
    }

    // 총알
    public void Bullet()
    {
        // 총알
        if (Input.GetKeyDown("space"))
        {
            // 프리팹의 복제품을 만들어냄
            // Instantiate() : 매개변수 오브젝트를 생성하는 함수
            GameObject playerbulletGo = GameObject.Instantiate(this.playerBulletprefab);

            // 생성 위치
            Vector3 targetPosition = this.transform.position;
            targetPosition.y += 0.598f;
            targetPosition.x -= 0.21f;

            // 위치 재설정
            playerbulletGo.transform.position = targetPosition;
        }
    }

    // 폭탄 생성
    public void Boom()
    {
        if(Input.GetKeyDown("b"))
        {
            // 해당 인스턴스를 생성
            GameObject boomGo = GameObject.Instantiate(this.Boomfab);

            // 생성 위치
            Vector3 targetPosition = this.transform.position;
            //targetPosition.y = 0f;
            //targetPosition.x = 0f;

            // 위치 재설정
            Boomfab.transform.position = targetPosition;

        }
    }
}

 

 

2.PlayerBulletController

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

public class PlayerBulletController : MonoBehaviour
{
    public float bulletMoveSpeed = 1f;    // 총알 속도

    private void Start()
    {
        // 코루틴 메서드를 호출할때 StartCoroutine(해당 메서드 이름)을 사용해야됨
        StartCoroutine(this.CoMove());
    }
    // Update is called once per frame
    //void Update()
    //{


    //    this.transform.Translate(Vector3.up * this.bulletMoveSpeed * Time.deltaTime);   

    //    // 일정 거리로 날라가면 해당 오브젝트를 삭제
    //    if(this.transform.position.y > 5.41f)
    //    {
    //        Object.Destroy(this.gameObject);
    //    }

    //}

    // 코루틴
    IEnumerator CoMove()
    {
        while (true)
        {
            // 수직으로 올라가는 총알
            this.transform.Translate(Vector2.up * this.bulletMoveSpeed * Time.deltaTime);

            // 총알이 일정 거리로 갔을때 총알을 삭제
            if (this.transform.position.y > 5.41f)
            {
                Object.Destroy(this.gameObject);
            }

            yield return null;
        }
       
    }
}

 

3. GamaManager

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

public class GamaManager : MonoBehaviour
{
    // Start is called before the first frame update
    public GameObject[] enemyObjs;

    // 적 생성 위치
    public Transform[] spawnPoints;

    public float maxSpanDelay; //  최고 시간
    public float curSpanDelay;  // 현재 흐르고 있는 시간

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

        if(curSpanDelay > maxSpanDelay)
        {
            SpawnEnemy();

            // 랜덤하게 딜레이 주기
            maxSpanDelay = Random.Range(0.5f, 3f);
            curSpanDelay = 0;
        }
    }

    void SpawnEnemy()
    {
        int ranEnemy = Random.Range(0, 3);      // 소환될 적
        int ranPoint = Random.Range(0, 5);      // 소환될 위치
        // 랜덤으로 정해진 적 프리펩, 생성 위치로 생성 로직 작성
        Instantiate(enemyObjs[ranEnemy],
            spawnPoints[ranPoint].position,
            spawnPoints[ranPoint].rotation);

    }

}

 

4. Boom

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

public class Boom : MonoBehaviour
{
    // boom 애니메이션을 사용하기위해 Animator 게임오브젝트 생성
    public Animator animator;

    void Update()
    {
        Destroy();
    }

    private void Destroy()
    {

        Object.Destroy(this.gameObject, 1);  // 1초후 삭제
    }
}

 

5.EnemyAController

using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using Unity.VisualScripting;
using UnityEditor;
using UnityEngine;

public class EnemyAController : MonoBehaviour
{
    public Animator animator;
    public GameObject explosoinEnemyfab;
    public float speed; // 떨어지는 속도
    public Rigidbody2D rb2d;
    private void Start()
    {
        //StartCoroutine(CoFade());
        // 떨어지는 속도
        rb2d.velocity = Vector2.down * speed;
    }


    //private void Fade()
    //{
    //    SpriteRenderer sr = this.GetComponent<SpriteRenderer>();

    //    for (float alpha = 1f; alpha >= 0; alpha -= 0.1f)
    //    {
    //        Color color = new Color(1, 0, 0, alpha);
    //        sr.color = color;
    //        Debug.Log(alpha);
    //    }
    //}

    //IEnumerator CoFade()
    //{
    //    SpriteRenderer sr = this.GetComponent<SpriteRenderer>();

    //    for (float alpha = 1f; alpha >= 0; alpha -= 0.1f)
    //    {
    //        Color color = new Color(1, 0, 0, alpha);
    //        sr.color = color;
    //        Debug.Log(alpha);
    //        // 다음 프레임으로 넘어갑니다.
    //        //yield return null;
    //        // 1초 있다가 다음 프레임으로 넘어간다.
    //        yield return new WaitForSeconds(1f);
    //    }
    //}

    // 해당 오브젝트가 isTrigger가 켜져있어야 활성화 된다.
    public void OnTriggerEnter2D(Collider2D collision)
    {
        // PlayerBullet(Clone)에 의해 충돌 이벤트가 발생할 경우
        if (collision.gameObject.name == "PlayerBullet(Clone)")
        {
            Debug.Log("총알이 호출됨");
            rb2d.velocity = Vector2.down * 0;
            Object.Destroy(collision.gameObject);//플레이어 블릿 게임오브젝트가 제거됨
            animator.SetInteger("EnemyAState", 1);
            //Object.Destroy(this.gameObject);    // 내가 붙어있는 게임오브젝트가 제거됨


            // 삭제하는 메서드를 코루틴으로 호출
            StartCoroutine(this.CoDestroy());
        }
        // PlayerBullet(Clone)에 의해 충돌 이벤트가 발생할 경우
        else if (collision.gameObject.name == "Boom(Clone)")
        {
            Debug.Log("붐이 호출됨");
            rb2d.velocity = Vector2.down * 0;
            animator.SetInteger("EnemyAState", 1);
            //Object.Destroy(collision.gameObject);//플레이어 Boom 게임오브젝트가 제거됨
            //Object.Destroy(this.gameObject);    // 내가 붙어있는 게임오브젝트가 제거됨

            // 삭제하는 메서드를 코루틴으로 호출
            StartCoroutine(this.CoDestroy());
        }
        // 맵 아래 끝 collision걸릴 경우
        //else if (collision.gameObject.name == "EndBox")
        //{

        //    Debug.Log("끝이 호출됨");
        //    Object.Destroy(this.gameObject);
        //}
    }
    

    // 코루틴을 이용한 해당 오브젝트 삭제
    IEnumerator CoDestroy(float delay = 1f)
    {
        // WaitForSeconds : 조정된 시간을 사용하여 일정시간동안 코루틴 사용을 실행 중지한다.
        yield return new WaitForSeconds(delay);
        Object.Destroy(this.gameObject);
    }
    
}