pudding81 2024. 3. 5. 17:20

 

간격이랑 속도 좀 조절해야할듯 ㅎㅎㅎㅎ

장애물이 넘나 하늘색이랑 보호색 ㅋㅋㅋㅋㅋㅋ

 

 

 

 

 

 

 

 

 

 

 

플레이어

 

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

public class UnirunPlayer : MonoBehaviour
{

    public Animator anim;
    private Rigidbody2D rb;
    private AudioSource playerAudio;


    public float jumpForce = 80f;
    public float moveForce = 3f;

    private int jumpCount; //점프 횟수
    private bool isGrounded=false; //바닥에 닿았는지
    private bool isDead = false; //죽었는지
    public AudioClip deathClip; 
   

    void Start()
    {
        this.rb = GetComponent<Rigidbody2D>();
        this.playerAudio = GetComponent<AudioSource>();
        this.anim = GetComponent<Animator>();

        
    }

   
    void Update()
    {
        if (isDead) //사망시 진행 종료
        { 
            return; 
        }

        Move();
        
    }

   void Move() //점프
    {
      
       
        
        if(Input.GetMouseButtonDown(0)&&jumpCount<2) //점프 최대횟수 2번
        {
           
            jumpCount++;

            //점프 직전에 속도를 제로
            this.rb.velocity = Vector3.zero;

            this.rb.AddForce(this.transform.up * this.jumpForce);

            playerAudio.Play();        

          

        }

        else if (Input.GetMouseButtonUp(0) && rb.velocity.y > 0)
        {
            //마우스에서손을 떼는 순간 속도를 절반으로 변경
            this.rb.velocity = this.rb.velocity * 0.5f;
        }

        int dirX = 0; 

        if (Input.GetKey(KeyCode.RightArrow)) //방향
        {
            dirX = 1;
        }

        if(Input.GetKey(KeyCode.LeftArrow)) 
        { 
            dirX = -1;
        }

        if(dirX!=0)
        {
            this.transform.localScale = new Vector3(dirX,1,1);
        }

        if (Mathf.Abs(this.rb.velocity.x) < 3) //이동속도 제한
        {
            this.rb.AddForce(this.transform.right * dirX * this.moveForce);

        }


    }

    void Die() //사망처리
    {
        this.anim.SetTrigger("Die");
        //떨어지면 
        this.isDead = true;
        //오디오 실행 
        playerAudio.clip = deathClip;
        playerAudio.Play();

        //속도를 제로로
        this.rb.velocity= Vector3.zero;

        //게임매니저 게임오버 처리 실행

        GameManager.instance.OnPlayerDead();

    }

    private void OnTriggerEnter2D(Collider2D other) 
    {
       if(other.tag=="Dead" && !isDead)
        {
            //데드존에 닿았을때
            Die();
        }


       

    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        //바닥에 닿았을때 첫번째 충돌지점
        //노말벡터의 y =-1 아래 /  y=0 오른쪽왼쪽 / y =1 위쪽
        // 0.7 45도 각도의 위쪽 
        //
        if (collision.contacts[0].normal.y>0.7f ) 
        {
            isGrounded = true;
            this.anim.SetBool("Grounded", isGrounded);
            jumpCount = 0;//누적 점프의 횟수를 0으로 리셋

        }
        
      

    }
    private void OnCollisionExit2D(Collision2D collision)
    {
        
        //바닥에서 벗어났을때
        isGrounded = false;
        this.anim.SetBool("Grounded", isGrounded);

    }

}

 

플랫폼

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

public class Platform : MonoBehaviour
{
    public GameObject[] obstacles;
    public bool stepped=false;

   

    private void OnEnable()
    {
        //발판을 리셋
        stepped = false;

        //장애물의 수만큼 반복 
        for(int i = 0; i < obstacles.Length; i++)
        {
            if (Random.Range(0, 3) == 0)
            {
                obstacles[i].SetActive(true); //3번중에 한번만 활성화 
            }
            else
            {
                obstacles[i].SetActive(false);
            }

        }


    }


    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.collider.tag == "Player" && !stepped)
        {
            //발판을 밟으면 점수 추가
            this.stepped = true;
            GameManager.instance.AddScore(1); //1점 추가

        }
    }
   




}

 

플랫폼 오브젝트 폴링으로 생성하기

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

public class PlatformSpawner : MonoBehaviour
{
    //오브젝트 풀링으로 발판만들기 
    public GameObject Platformprefab;
    public int count=3;
    private GameObject[] platforms;
    private Vector2 poolPosition=new Vector2(0,-25);
    
    private float timeSpawn;
    private float lasttimeSpawn;
    private int currentIndex;

    void Start()
    {
        //발판 미리 생성
        platforms = new GameObject[count];

        for (int i = 0; i < count; i++)
        {
            platforms[i]= Instantiate(Platformprefab,poolPosition,Quaternion.identity);

        }

        lasttimeSpawn = 0; //마지막 배치시점 초기화 

        timeSpawn = 0; //시간간격 초기화 

    }

   
    void Update()
    {

       
        if(GameManager.instance.isGameOver) 
        {
            return;
        }

        //순서를 돌아가며 발판을 배치 
        // Time.time 마지막 배치시점 
        if (Time.time >= lasttimeSpawn +timeSpawn)
        {
            lasttimeSpawn = Time.time;
           
            //배치 시간
            timeSpawn = Random.Range(1.5f,3.5f);
            
            //배치 높이
            float ypos = Random.Range(-3f, 1.5f);

            //발판 비활성화 활성화
            platforms[currentIndex].SetActive(false);
            platforms[currentIndex].SetActive(true);

            // 오른쪽에 재배치
            platforms[currentIndex].transform.position = new Vector2(13f, ypos);

            currentIndex++;

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

            }

        }

    }
}

 

게임매니저 

게임 점수 표시 , 게임오버 후 재시작

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

public class GameManager : MonoBehaviour
{
   
    public static GameManager instance;//싱글톤

    public bool isGameOver=false;
    public Text scoreText;
    public int score=0;
    public GameObject gameover;


    private void Awake()
    {
      if (instance == null)
        {
            instance = this;
        }
        
       else
        {
            //게임매니저는 씬에 1개만
            Destroy(gameObject);

        }
    }

    private void Update()
    {
        //게임오버에서 게임을 재시작
        if(isGameOver && Input.GetMouseButtonDown(0)) 
        { 
            SceneManager.LoadScene(SceneManager.GetActiveScene().name);//현재씬 재시작
        }
        

    }

    public void AddScore(int newscore)
    {
        if(!isGameOver)
        {
            //점수 표시
            score += newscore;
            this.scoreText.text = "Score : " + score;
        }
       


    }

   
    public void OnPlayerDead()
    {
        //게임오버 
        isGameOver = true;
        gameover.SetActive(true);


     } 




}

 

스크롤링 - 이동하기 

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

public class Scrolling : MonoBehaviour
{
   

    public float speed=10f;



    
    void Update()
    {
        if(!GameManager.instance.isGameOver)
        {
            //게임오브젝트를 왼쪽으로 움직임
            this.transform.Translate(Vector3.left * speed * Time.deltaTime);
        }
       


    }
}

 

배경 무한 반복재생하기

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

public class BackgroundLoop : MonoBehaviour
{
    private float width; //배경의 가로길이
    private void Awake()
    {
        //가로길이를 측정
        BoxCollider2D boxCollider = GetComponent<BoxCollider2D>();
        width = boxCollider.size.x;
        //Debug.Log(width);
    }
    
   
    void Update()
    {
        //현재위치가 width 이상 됐을때 위치 재배치

        if(transform.position.x<=-width)
        {
            RePosition();
        }

    }

    private void RePosition()
    {
        //위치를 재배치
        //현재위치에서 가로길이 2배만큼 오른쪽으로 이동

        Vector2 offset =new Vector2(this.width * 2,0);

        this.transform.position = (Vector2)this.transform.position+offset;



    }

}