UNITY/Unity Study

유니티 시민강좌 2일차

GREEN나무 2023. 7. 19. 08:56
728x90

 

 

배경화면 움직이기(플레이하는 동안 반복)

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

public class BackgroundRepeat : MonoBehaviour
{
    public float scrollSpeed = 0.9f;
    //스크롤할 속도를 상수로 지정해 줍니다. 
    private Material thisMaterial;
    //Quad의 Material 데이터를 받아올 객체를 선언합니다. 
    void Start()
    {
        //객체가 생성될때 최초 1회만 호출 되는 함수 입니다. 
        thisMaterial = GetComponent<Renderer>().material;
        //현재 객체의 Component들을 참조해 Renderer라는 컴포넌트의 Material정보를 받아옵니다. 
    }
    void Update()
    {
        Vector2 newOffset = thisMaterial.mainTextureOffset;
        // 새롭게 지정해줄 OffSet 객체를 선언합니다. 
        newOffset.Set(0, newOffset.y + (scrollSpeed * Time.deltaTime));
        // Y부분에 현재 y값에 속도에 프레임 보정을 해서 더해줍니다. 
        thisMaterial.mainTextureOffset = newOffset;
        //그리고 최종적으로 Offset값을 지정해줍니다. 
    }
}

 

키보드로 - Input.GetKey(KeyCode.Space)
마우스로 - Input.GetMouseButtonDown(0) //0은 왼쪽, 1은 오른쪽 커서

예시

더보기

 

 public class Player : MonoBehaviour
{
    public float moveSpeed = 5.0f;
    public GameObject firePrefab;
    public bool canShoot = true;
    public float shootDelay = 0.5f;
    float shootTimer = 0;
    public GameManager gameManager;

    public GameObject ParticleFXExplosion;
    private List<GameObject> instantiatedFirePrefabs = new List<GameObject>();

   
    void Update()
    {
        moveControl();
        ShootControl();
    }

	...


    void ShootControl()
    {
        if (canShoot)
        {
            if (shootTimer > shootDelay && (Input.GetKey(KeyCode.Space) || Input.GetMouseButtonDown(0)))
            {
                GameObject newFirePrefab = Instantiate(firePrefab, transform.position, Quaternion.identity);
                instantiatedFirePrefabs.Add(newFirePrefab);
                shootTimer = 0;
            }
            shootTimer += Time.deltaTime;
        }
    }

	...

}

부딪치면 파괴하기

    void OnTriggerEnter2D(Collider2D other)
    { // 콜리더가 2D나 3D중 하나로만 통일시키기
        if (other.gameObject.tag.Equals("Enemy") || other.gameObject.tag.Equals("Blue"))
        {
            Destroy(other.gameObject); // 상대편 소멸
            Destroy(this.gameObject); 
            Instantiate(ParticleFXExplosion, transform.position, Quaternion.identity);
            // 폭발 효과
        }
    }

 

 

총알 설정

플레이어 공격

using UnityEngine;

public class fire : MonoBehaviour
{
    public float moveSpeed = 0.45f;
    public GameObject ParticleFXExplosion;

    void Update()
    {
        float moveY = moveSpeed * Time.deltaTime;
        transform.Translate(0, moveY, 0);
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.tag.Equals("Enemy"))
        {
            ScoreManager.instance.ComputeScore(1);
            Destroy(other.gameObject);
            Destroy(this.gameObject);
            Instantiate(ParticleFXExplosion, transform.position, Quaternion.identity);          
        }
    }

    void OnBecameInvisible()
    {
        Destroy(this.gameObject);
    }
}

 

 

적의 공격

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

public class EnermyBall : MonoBehaviour
{
    public float moveSpeed = 2.0f; //총알이 움직일 속도를 상수로 지정해줍시다. 

    public GameObject ParticleFXExplosion; // 충돌 시 폭발 이펙트
    void Start()
    {
    }
    void Update()
    {
        float moveY = -moveSpeed * Time.deltaTime;         //이동할 거리를 지정해 줍시다. 
        transform.Translate(0, moveY, 0);    //이동을 반영해줍시다. 
    }

    void OnTriggerEnter2D(Collider2D other)
    //rigidBody가 무언가와 충돌할 때 호출되는 함수 입니다.
    //Collider2D other로 부딪힌 객체를 받아 옵니다.
    {
        if (other.gameObject.tag.Equals("Dragon"))
        //부딪힌 객체의 태그를 비교해서 적인지 판단합니다.
        {

            Destroy(other.gameObject);
            //적을 파괴합니다.
            Destroy(this.gameObject);
            //자신을 파괴합니다.
            Instantiate(ParticleFXExplosion, transform.position, Quaternion.identity);
            //폭발이펙트
            //폭발이펙트
        }
    }
    void OnBecameInvisible() //화면 밖으로 나가 보이지 않게 되면 호출이 된다.
    {
        Destroy(this.gameObject); //객체를 삭제한다.
    }
}

 

 

 


void OnBecameInvisible() 이벤트 - 화면 밖으로 안보이게 되면 호출되는 함수 
void OnBecameInvisible()
{
 Destroy(this.gameObject);// 자기 자신을 지움.
}

 

시간두고 소멸시키기

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


public class explosion : MonoBehaviour
{
    void Start()
    {
        Destroy(this.gameObject, 0.8f);
        //객체가 생성된 뒤 0.8초 뒤에 객체를 삭제합니다.
    }
    void Update()
    {
    }
}



자동생성

using UnityEngine;
using System.Collections;

public class spawnManager : MonoBehaviour
{
    public bool enableSpawn = true;
    public GameObject Enemy; //Prefab을받을 public변수 입니다.
    void SpawnEnemy()
    {
        float randomX = Random.Range(-8.0f, 8.0f); //적이 나타날 X좌표를 랜덤으로 생성해 줍니다.
        if (enableSpawn)
        {
            GameObject enemy = (GameObject)Instantiate(Enemy, new Vector3(randomX, 23.0f, 1.0f), Quaternion.identity); 
		//랜덤한 위치와, 화면 제일 위에서 Enemy를 하나 생성.
        }
    }

    void Start()
    {
        InvokeRepeating("SpawnEnemy", 1, 1); //1초후 부터, SpawnEnemy함수를 1초마다 반복해서 실행.
    }

    void Update()
    {
    }
}

 

플레이어, 적 코드

더보기

플레이어

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

public class Player : MonoBehaviour
{
    public float moveSpeed = 5.0f;
    public GameObject firePrefab;
    public bool canShoot = true;
    public float shootDelay = 0.5f;
    float shootTimer = 0;
    public GameManager gameManager;

    public GameObject ParticleFXExplosion;
    private List<GameObject> instantiatedFirePrefabs = new List<GameObject>();

    void Start()
    {
        // 초기화 코드를 작성합니다.
    }

    void Update()
    {
        moveControl();
        ShootControl();
    }

    void moveControl()
    {
        float distanceX = Input.GetAxis("Horizontal") * Time.deltaTime * moveSpeed;
        this.gameObject.transform.Translate(distanceX, 0, 0);

        Vector3 viewPos = Camera.main.WorldToViewportPoint(transform.position);
        viewPos.x = Mathf.Clamp01(viewPos.x);
        viewPos.y = Mathf.Clamp01(viewPos.y);
        Vector3 worldPos = Camera.main.ViewportToWorldPoint(viewPos);
        transform.position = worldPos;
    }

    void ShootControl()
    {
        if (canShoot)
        {
            if (shootTimer > shootDelay && (Input.GetKey(KeyCode.Space) || Input.GetMouseButtonDown(0)))
            {
                GameObject newFirePrefab = Instantiate(firePrefab, transform.position, Quaternion.identity);
                instantiatedFirePrefabs.Add(newFirePrefab);
                shootTimer = 0;
            }
            shootTimer += Time.deltaTime;
        }
    }


    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.tag.Equals("Enemy") || other.gameObject.tag.Equals("Blue"))
        {
            Destroy(other.gameObject);
            Destroy(this.gameObject);
            Instantiate(ParticleFXExplosion, transform.position, Quaternion.identity);

            gameManager.PlayerDied();
        }
    }
}

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Enemy : MonoBehaviour
{
    public GameObject bluePrefab; // 발사할 탄을 저장합니다.
    public bool canShoot = true; // 탄을 쏠 수 있는 상태인지 검사합니다.
    public float shootDelay = 2.0f; // 탄을 쏘는 주기를 정해줍니다.
    float shootTimer = 0; // 시간을 잴 타이머를 만들어줍니다.
    private List<GameObject> instantiatedBluePrefabs = new List<GameObject>();

    void Update()
    {
        ShootControl(); // 발사를 관리하는 함수입니다.
    }
    
    void ShootControl()
    {
        if (canShoot)
        {   // 2초에 한번 발사
            if (shootTimer > shootDelay )
            {
                GameObject newFirePrefab = Instantiate(bluePrefab, transform.position, Quaternion.identity);
                instantiatedBluePrefabs.Add(newFirePrefab);
                shootTimer = 0;
            }
            shootTimer += Time.deltaTime;
        }
    }
}

 

스코어

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

public class ScoreManager : MonoBehaviour
{
    public static ScoreManager instance;

    public TextMeshPro scoreText; // UI아님, TextMeshPro만 넣을 수 있음
    public int score = 0;

    private void Awake()
    {
        instance = this;
    }

    private void Start()
    {
        UpdateScore();
    }

    public void UpdateScore()
    {
        scoreText.text = score.ToString();
    }

    public void ResetScore()
    {
        score = 0;
        UpdateScoreText();
    }

    public void ComputeScore(int num)
    {
        score += num;
        UpdateScore();
    }

    private void UpdateScoreText()
    {
        scoreText.text = "Score: " + score.ToString();
    }
}

 

정지, 재시작, 나가기 버튼 (UI)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class GameManager : MonoBehaviour
{
    public GameObject pauseUI;

    public Text count_Text;
    public GameObject iMG;
    public float restartDelay = 4f; // 재시작 딜레이 시간
    private float restartTimer; // 재시작 카운트다운 타이머

    public void Start()
    {
        pauseUI.SetActive(false);
        iMG.gameObject.SetActive(false);
    }

    public void OnPauseButton()
    {
        pauseUI.SetActive(true);
        Time.timeScale = 0; // 일시정지
    }

    public void OnContinueButton()
    {
        pauseUI.SetActive(false);
        Time.timeScale = 1;
    }

    public void OnQuitButton()
    {
#if UNITY_EDITOR
        UnityEditor.EditorApplication.isPlaying = false;
#else
        Application.Quit();
#endif
    }

	...
    
}

 

플레이어 사망 후 다시 시작

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class GameManager : MonoBehaviour
{
    public GameObject pauseUI;

    public Text count_Text;
    public GameObject iMG;
    public float restartDelay = 4f; // 재시작 딜레이 시간
    private float restartTimer; // 재시작 카운트다운 타이머

    public void Start()
    {
        pauseUI.SetActive(false);
        iMG.gameObject.SetActive(false);
    }
    
...

    public void PlayerDied()
    {
        StartCoroutine(RestartGameAfterDelay());
        //count_Text.gameObject.SetActive(true);

        iMG.gameObject.SetActive(true);
    }
    IEnumerator Count()
    {
        count_Text.text = "3";
        yield return new WaitForSeconds(1.0f);

        count_Text.text = "2";
        yield return new WaitForSeconds(1.0f);

        count_Text.text = "1";
        yield return new WaitForSeconds(1.0f);

        count_Text.text = "Go!";
    }


    IEnumerator RestartGameAfterDelay()
    {
        StartCoroutine(Count());
        yield return new WaitForSeconds(4f);

        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);

    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class Player : MonoBehaviour
{
	...
    
    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.tag.Equals("Enemy") || other.gameObject.tag.Equals("Blue"))
        {
            Destroy(other.gameObject);
            Destroy(this.gameObject);
            Instantiate(ParticleFXExplosion, transform.position, Quaternion.identity);

            gameManager.PlayerDied();  // 게임메니저의 플레이어 죽음 호출
        }
    }
}

 

 

 

 

'UNITY > Unity Study' 카테고리의 다른 글

유니티 시민강좌 3일  (0) 2023.07.19
유니티 시민강좌 1,2일차 세로 게임  (0) 2023.07.19
유니티 시민강좌 1일차  (0) 2023.07.17
운수룰렛 스와이프로 바꾸기  (0) 2023.07.05
카메라 컨트롤  (0) 2023.07.05