Unity/Project : Unity 2D 쿠키런

Unity 2D 쿠키런 21.04.13

HappyFrog 2021. 4. 19. 21:38

04.13

-button 구현

-restart 구현

 

-장애물 구현했지만 아직 못 찾아낸 원인으로 캐릭터에게 도달하기 전에 없어지는 경우 발생. 

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

public class CookieController : MonoBehaviour
{
    public AudioClip deathClip;

    Rigidbody2D playerRigid2D;
    AudioSource playerAudio;
    Animator animator;
    float jumpForce = 400f;
    bool isDie = false;
    bool isGrounded = false;
    int jumpCount = 0;
    bool doubleJump = false;
    bool isSlide = false;
    bool onJumpClick = false;

    // Start is called before the first frame update
    void Start()
    {
        this.playerRigid2D = this.GetComponent<Rigidbody2D>();
        this.animator = this.GetComponent<Animator>();
        this.playerAudio = this.GetComponent<AudioSource>();

    }

    // Update is called once per frame
    void Update()
    {
        if (this.isDie) return;

        this.animator.SetBool("Grounded", this.isGrounded);

        if (!GameManager.instance.isJump() && this.playerRigid2D.velocity.y > 0)
        {
            this.playerRigid2D.velocity = this.playerRigid2D.velocity * 0.75f;
        }
        this.animator.SetBool("Grounded", this.isGrounded);
        this.animator.SetBool("Double", this.doubleJump);
        this.animator.SetBool("Slide", this.isSlide);

        if (GameManager.instance.IsOver())
        {
            GameManager.instance.GameOver();
            this.Die();
        }
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag == "Dead")
        {
            GameManager.instance.GameOver();
        }
    }

    public void Jump()
    {
        if (this.jumpCount < 2)
        {
            this.isSlide = false;
            this.isGrounded = false;
            this.jumpCount++;
            if (this.jumpCount == 2)
            {
                this.doubleJump = true;
            }
            this.playerRigid2D.velocity = Vector2.zero;

            this.playerRigid2D.AddForce(new Vector2(0, this.jumpForce));
        }

    }

    public void Slide()
    {
        this.isSlide = true;
        this.animator.SetBool("Slide", this.isSlide);
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.contacts[0].normal.y > 0.7f)
        {
            this.isGrounded = true;
            this.jumpCount = 0;
            this.doubleJump = false;
        }
    }

    private void Die()
    {
        this.isDie = true;
        this.animator.SetTrigger("Die");
        this.playerRigid2D.velocity = Vector2.zero;
    }

    public void StopSlide()
    {
        this.isSlide = false;
        this.animator.SetBool("Slide", this.isSlide);
    }

    public void StopJump()
    {
        this.onJumpClick = false;
    }

    public void StartJump()
    {
        this.onJumpClick = true;
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObsSpawner : MonoBehaviour
{
    public GameObject ObsPrefab;
    public GameObject ObsPrefab2;
    public int count = 3;
    private GameObject prefab;

    public float timeBetSpawnMin = 1.25f;
    public float timeBetSpawnMax = 2.25f;
    private float timeBetSpawn;

    public float yMin = -3f;
    public float yMax = 1.5f;
    private float xPos = 20;

    private GameObject[] obs;
    private int currentIndex = 0;

    private Vector2 poolPosition = new Vector2(0, -25);
    private float lastSpawnTime;
    // Start is called before the first frame update
    void Start()
    {
        int num = Random.Range(0, 2);
        if (num == 0) this.prefab = ObsPrefab;
        else this.prefab = ObsPrefab2;

        obs = new GameObject[count];

        for(int i = 0; i < count; i++)
        {
            obs[i] = Instantiate(this.prefab, poolPosition, Quaternion.identity);
        }

        lastSpawnTime = 0f;
        timeBetSpawn = 0f;
    }

    // Update is called once per frame
    void Update()
    {
        if (GameManager.instance.IsOver()) return;

        if(Time.time >= lastSpawnTime + timeBetSpawn)
        {
            lastSpawnTime = Time.time;

            timeBetSpawn = Random.Range(timeBetSpawnMin, timeBetSpawnMax);

            float yPos = Random.Range(yMin, yMax);

            obs[currentIndex].SetActive(false);
            obs[currentIndex].SetActive(true);

            obs[currentIndex].transform.position = new Vector2(xPos, yPos);

            currentIndex++;

            if (currentIndex >= count) currentIndex = 0;
        }

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

public class Obstacles : MonoBehaviour
{
    public GameObject[] obstacles;

    bool stepped = false;

    private void OnEnable()
    {
        stepped = false;

        for(int i = 0; i < obstacles.Length; i++)
        {
            if(Random.Range(0,3) == 3)
            {
                obstacles[i].SetActive(true);
            }
            else
            {
                obstacles[i].SetActive(false);
            }
        }
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if(collision.collider.tag == "Player")
        {
            stepped = true;
            GameManager.instance.AddScore(200);
        }
    }
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if(this.transform.position.x <= -21)
        {
            Destroy(this.gameObject);
        }
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class Jump : MonoBehaviour
{
    
    // Start is called before the first frame update
    void Start()
    {
        EventTrigger eventTriggers = gameObject.GetComponent<EventTrigger>();

        EventTrigger.Entry entry_PointerDown = new EventTrigger.Entry();
        entry_PointerDown.eventID = EventTriggerType.PointerDown;
        entry_PointerDown.callback.AddListener((data) => GameManager.instance.JumpOn());
        eventTriggers.triggers.Add(entry_PointerDown);

        EventTrigger.Entry entry_PointerUp = new EventTrigger.Entry();
        entry_PointerUp.eventID = EventTriggerType.PointerUp;
        entry_PointerUp.callback.AddListener((data) => GameManager.instance.JumpOff());
        eventTriggers.triggers.Add(entry_PointerUp);
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class Slide : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        EventTrigger eventTrigger = gameObject.AddComponent<EventTrigger>();

        EventTrigger.Entry entry_PointerDown = new EventTrigger.Entry();
        entry_PointerDown.eventID = EventTriggerType.PointerDown;
        entry_PointerDown.callback.AddListener((data) => GameManager.instance.SlideOn());
        eventTrigger.triggers.Add(entry_PointerDown);

        EventTrigger.Entry entry_PointerUp = new EventTrigger.Entry();
        entry_PointerUp.eventID = EventTriggerType.PointerUp;
        entry_PointerUp.callback.AddListener((data) => GameManager.instance.SlideOff());
        eventTrigger.triggers.Add(entry_PointerUp);
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using UnityEngine.EventSystems;

public class GameManager : MonoBehaviour
{
    public UI ui;
    public static GameManager instance;

    bool isOver = false;
    GameObject stage;
    ScrollObjects scrollOb;
    bool jump = false;
    bool slide = false;
    float scoreDelta;
    int score = 0;
    float delta;
    HpGauge hpGauge;
    CookieController cookie;
    GameObject ginger;

    private void Awake()
    {
        this.ginger = GameObject.Find("Ginger");
        this.cookie = this.ginger.GetComponent<CookieController>();

        if (GameManager.instance == null)
        {
            GameManager.instance = this;
        }
        else if (GameManager.instance != null)
        {
            Debug.LogFormat("이미 게임매니저 객체가 존재합니다");
            Object.Destroy(this.gameObject);
        }
    }
    
    void Start()
    {
        
    }
    
    void Update()
    {
        this.ui.Score.GetComponent<Text>().text = "Score " + this.score;

        if (this.slide)
        {
            this.cookie.Slide();
        }
        else if (!this.slide)
        {
            this.cookie.StopSlide();
        }
                
        if (!this.isOver)
        {
            CheckScore();
        }        
    }

    private void CheckScore()
    {
        this.scoreDelta += Time.deltaTime;
        if (this.scoreDelta > 1.0f)
        {
            this.scoreDelta = 0;
            this.score += 150;
        }
    }

    public void GameOver()
    {
        this.isOver = true;
        this.ui.GameOver.gameObject.SetActive(true);
        if (Input.anyKeyDown) this.Restart();
    }

    public bool IsOver()
    {
        return this.isOver;
    }

    private void Restart()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }
    public void SlideOn()
    {
        this.slide = true;
    }
    public void SlideOff()
    {
        this.slide = false;
    }
    public void JumpOn()
    {
        this.jump = true;
        this.cookie.Jump();
    }
    public void JumpOff()
    {
        this.jump = false;
    }
    public bool isJump()
    {
        return this.jump;
    }
    public void AddScore(int score)
    {
        this.score += score;
    }
}

버튼으로 변환시키는 것 때문에 골머리를 앓았는데 이벤트 트리거를 검색해서 찾아보고 적용하니 금방 해결됐다.

내가 못쓰는 이벤트... 편한 이벤트...