2023년 5월 28일 일요일

unity 2D 슈팅 게임 코드 정리


animation 만들기 : *.anim

- 멀티 이미지 drag & drop


충돌 컴포넌트

- Circle Collider 2D

- Box Collider 2D


중력 처리 컴포넌트

- Rigidbody 2D


패널

UI > Panel

Canvas > Canvas Scaler > UI Scale Mode 조정


일정 시간 후 함수 동작

Invoke("함수명", 시간);


원하는 object 찾기

Player player = FindObjectOfType<Player>();


씬로딩하기

using UnityEngine.SceneManagement;

...

ScenManager.LoadScene("씬이름")



물리 속성 가져와서 변경하기

Rigidbody2D rb = GetComponent<Rigidbody2D>();

rb.velocity = Vector2.up * 3;


마우스 버튼

if (Input.GetMouseButtonDown(0))

{

    // 왼쪽 버튼이 눌렸다

}


이동 거리 보정

transform.position += Vector3.left * Time.deltaTime;


background scroll

    private float moveSpeed = 3;
    // Update is called once per frame
    void Update()
    {
        //transform.position += Vector3.down * moveSpeed;
        transform.position += Vector3.down * moveSpeed * Time.deltaTime;
        if (transform.position.y<-10)
        {
            transform.position += new Vector3(0, 20, 0);
        }
    }


키보드로 움직이기

    [SerializeField]
    private float moveSpeed;
    // Update is called once per frame
    void Update()
    {
        Vector3 moveToLR = new Vector3(moveSpeed * Time.deltaTime, 0, 0);
        Vector3 moveToUD = new Vector3(0, moveSpeed * Time.deltaTime, 0);

        if (Input.GetKey(KeyCode.RightArrow))
        {
            transform.position += moveToLR;
        }
        else if (Input.GetKey(KeyCode.LeftArrow))
        {
            transform.position -= moveToLR;
        }
        else if (Input.GetKey(KeyCode.UpArrow))
        {
            transform.position += moveToUD;
        }
        else if (Input.GetKey(KeyCode.DownArrow))
        {
            transform.position -= moveToUD;
        }
    }


마우스 위치로 이동

    void Update()
    {
        Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        float tox = Mathf.Clamp(mousePos.x, -2.4f, 2.4f);
        float toy = Mathf.Clamp(mousePos.y, -2.4f, 2.4f);
        transform.position = new Vector3(tox, toy, transform.position.z);
    }


무기 발사

weapon(무기), shootpos(발사 위치) 설정 필요

    public GameObject weapon;
    public Transform shootpos;
    public float shootInterval = 1.0f;
    private float lastshoottime = 0f;

    void Shoot()
    {
        if (Time.time -lastshoottime > shootInterval)
        {
            Instantiate(weapon, shootpos.position, Quaternion.identity);
            lastshoottime = Time.time;
        }
    }


무기(총알)

    // Start is called before the first frame update
    void Start()
    {
        Destroy(gameObject, 2f);
    }
    public float moveSpeed = 10;
    // Update is called once per frame
    void Update()
    {
        transform.position += Vector3.up * moveSpeed *Time.deltaTime;
    }


EnemySpawner Enemy 무한 생성, 코루틴 이용

public class EnemySpawner : MonoBehaviour
{
    public GameObject[] enemies;
    private float[] arrPosX = { -2.2f, -1.1f, 0, 1.1f, 2.2f };
    // Start is called before the first frame update

    void Start()
    {
        StartCoroutine("EnemyRoutine");
    }

    // 코루틴 사용
    IEnumerator EnemyRoutine()
    {
        yield return new WaitForSeconds(3.0f);
        while(true){
            int index = Random.Range(0,enemies.Length);
            int iposX = Random.Range(0,arrPosX.Length);
            SpawnerEnemy(arrPosX[iposX], index);
            yield return new WaitForSeconds(1f);
        }

    }

    void SpawnerEnemy(float posX, int index)
    {
        Vector3 spawnPos = new Vector3(posX, transform.position.y, transform.position.z);
        GameObject obj = Instantiate(enemies[index], spawnPos, Quaternion.identity);
        // 다른 object의 멤버 값을 변경
        Enemy enemy = obj.GetComponent<Enemy>();
        enemy.moveSpeed = Random.Range(1,5);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}


Enemy 충돌 처리

public class Enemy : MonoBehaviour
{
    public float moveSpeed = 3f;
    private float minY = -7f;
    private float hp = 1f;
    // Update is called once per frame
    void Update()
    {
        transform.position += Vector3.down * moveSpeed *Time.deltaTime;
        if (transform.position.y < minY ){
            Destroy(gameObject);
        }
    }

    // Box Collider 2D 컴포넌트 사용
    // Is Trigger : On
    private void OnTriggerEnter2D(Collider2D other) {
        // 충돌 대상은 gameObject tag로 분류함
        if (other.gameObject.tag=="weapon"){
            Weapon weapon = other.gameObject.GetComponent<Weapon>();
            hp -= weapon.damage;
            if (hp <= 0){
                // Enemy 삭제
                Destroy(gameObject);
                // 폭발 장면
            }
            // Weapon 삭제
            Destroy(other.gameObject);            
        }
    }
}


적 파괴 후 item(Coin) 의 움직임, 포물선 운동이 되도록

public class Coin : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        CoinJump();
    }

    // Coin 공을 하늘로 던져서 포물선 그리면서 내려오도록 랜덤
    void CoinJump(){
        Rigidbody2D rb = GetComponent<Rigidbody2D>();
        float randjf = Random.Range(4f,8f);
        Vector2 v2 = Vector2.up * randjf;
        v2.x = Random.Range(-2f,2f);
        rb.AddForce(v2, ForceMode2D.Impulse);
    }

    // Update is called once per frame
    void Update()
    {
        // Coin 화면에서 벗어나면 삭제한다
        if (transform.position.y < -7 ){
            Destroy(gameObject);
        }
    }
}


플레이어: 충돌 처리, 께임 끝, 코인 사라지는 코드

public class player : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }
    [SerializeField]
    private float moveSpeed;
    public GameObject weapon;
    public Transform shootpos;
    public float shootInterval = 1.0f;
    private float lastshoottime = 0f;

    // Update is called once per frame
    void Update()
    {
        Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        float tox = Mathf.Clamp(mousePos.x, -2.4f, 2.4f);
        float toy = Mathf.Clamp(mousePos.y, -2.4f, 2.4f);
        transform.position = new Vector3(tox, toy, transform.position.z);
        Shoot();
    }
    void Shoot()
    {
        if (Time.time -lastshoottime > shootInterval)
        {
            Instantiate(weapon, shootpos.position, Quaternion.identity);
            lastshoottime = Time.time;
        }
    }
    private void OnTriggerEnter2D(Collider2D other) {
        if (other.gameObject.tag == "Enemy"){
            // 게임 끝남
            Destroy(gameObject);
        }else if (other.gameObject.tag == "Coin"){
            // 코인 사라짐
            Destroy(other.gameObject);
        }
    }
}


Text 사용

using TMPro;
...
    [SerializeField]
    private TextMeshProUGUI text;
...

    text.SetText(score.ToString());


Single tone instance

public class GameManager : MonoBehaviour
{
    public static GameManager instance = null;
    void Awake() {
        if (instance==null){
            instance = this;
        }
    }
}







댓글 없음:

댓글 쓰기