본문 바로가기
2D 콘텐츠 제작 개발일지 (mario)

슈퍼마리오 전체코드

by 노재두내 2023. 9. 21.
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using static UnityEditor.Progress;

public class BrickCoinController : MonoBehaviour
{
    private Animator anim;
    [SerializeField]
    private GameObject coinPrefab;
    private bool isCrashed = false;
    //public System.Action<ItemGenerator.eItemType> onChanged;
    // Start is called before the first frame update
    void Start()
    {
        this.anim = this.GetComponent<Animator>();
    }

    // Update is called once per frame

    public void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "mario")
        {
            this.anim.SetBool("isCrashed", true);
            if (isCrashed == false)
            {
                Instantiate(coinPrefab, new Vector3(transform.position.x, transform.position.y + 1.2f, transform.position.z), transform.rotation);
                isCrashed = true;
            }
        }
    }

}
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using static UnityEditor.Progress;

public class BrickMushroomController : MonoBehaviour
{
    private AudioSource audioSource;
    [SerializeField]
    private AudioClip mushroomProduceSfx;
    private Animator anim;
    [SerializeField]
    private GameObject mushroomPrefab;
    private bool isCrashed = false;
    //public System.Action<ItemGenerator.eItemType> onChanged;
    // Start is called before the first frame update
    void Start()
    {
        this.audioSource = this.GetComponent<AudioSource>();
        this.anim = this.GetComponent<Animator>();
    }

    // Update is called once per frame

    public void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "mario")
        {
            this.anim.SetBool("isCrashed", true);
            if (isCrashed == false)
            {
                Instantiate(mushroomPrefab, new Vector3(transform.position.x, transform.position.y + 0.9f, transform.position.z), transform.rotation);
                this.audioSource.PlayOneShot(this.mushroomProduceSfx);
                isCrashed = true;
            }
        }
    }

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

public class CameraController : MonoBehaviour
{

    
    private Transform playerTransform;
    [SerializeField]
    Vector3 cameraPosition;

    [SerializeField]
    Vector2 center;
    [SerializeField]
    Vector2 mapSize;

    [SerializeField]
    float cameraMoveSpeed;
    float height;
    float width;


    public void Init()//시작하자마자 말고, 호출될때 (마리오 생성되고) 호출되어야함
    {
        playerTransform = GameObject.Find("Mario").GetComponent<Transform>();//생성된 마리오 이름의 오브젝트의 위치를 찾아서 저장

        height = Camera.main.orthographicSize;
        width = height * Screen.width / Screen.height;
    }


    void FixedUpdate()
    {
        LimitCameraArea();
    }

    void LimitCameraArea()
    {
        //초기화 되기전에는 호출되면 안됨 
        if (playerTransform == null) return;

        transform.position = Vector3.Lerp(transform.position,
                                          playerTransform.position + cameraPosition,
                                          Time.deltaTime * cameraMoveSpeed);
        float lx = mapSize.x - width;
        float clampX = Mathf.Clamp(transform.position.x, -lx + center.x, lx + center.x);

        float ly = mapSize.y - height;
        float clampY = Mathf.Clamp(transform.position.y, -ly + center.y, ly + center.y);

        transform.position = new Vector3(clampX, clampY, -10f);
    }

    private void OnDrawGizmos()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireCube(center, mapSize * 2);
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;
using System.Linq;

public class DataManager : MonoBehaviour
{
    public static readonly DataManager instance = new DataManager();
    private Dictionary<int, MarioData> dicMarioDatas = new Dictionary<int, MarioData>();
    public void LoadMarioData()
    {
        TextAsset asset= Resources.Load<TextAsset>("mario_data");
        string json = asset.text;
        Debug.Log(json);
        var marioDatas = JsonConvert.DeserializeObject<MarioData[]>(json);
        Debug.LogFormat("arrMarioDatas.length:{0}", marioDatas.Length);

        foreach(var marioData in marioDatas)
        {
            this.dicMarioDatas.Add(marioData.id, marioData);
        }
        Debug.LogFormat("mario_data 에셋을 로드 했습니다. {0}", this.dicMarioDatas.Count);
    }

    public List<MarioData> GetMarioDatas()
    {
        return this.dicMarioDatas.Values.ToList();

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

public class FlagController : MonoBehaviour
{
    private AudioSource audioSource;
    [SerializeField]
    private AudioClip gameOverSfx;
    [SerializeField]
    private GameObject flagGo;
    [SerializeField]
    private float moveSpeed = 0.5f;
    [SerializeField]
    private Transform handle;
    private MarioController marioController;
    private bool isInFlag = false;
    private bool canKey = true;
    // Start is called before the first frame update
    void Start()
    {
        this.audioSource = this.GetComponent<AudioSource>();
        isInFlag = false;
    }
    // Update is called once per frame
    void Update()
    {
        
    }
    
    private void OnTriggerEnter2D(Collider2D collision)
    {
        Debug.Log(collision.tag);

        if (collision.CompareTag("mario"))
        {
            MarioController mario = GameObject.Find("Mario").GetComponent<MarioController>();

            //마리오는 더이상 인풋을 받지 못함 
            mario.IgnoreInput(true);
        

            Rigidbody2D mRigid = mario.GetComponent<Rigidbody2D>();

            //현재 속도를 0으로 만듬 
            mRigid.velocity = Vector3.zero;
            mRigid.angularVelocity = 0;

            //부모를 핸들로 설정 
            mario.transform.SetParent(this.handle);

            //물리 영향을 안받게 설정 
            mRigid.isKinematic = true;

            //마리오 위치
            handle.transform.position = new Vector3(handle.transform.position.x, mario.transform.position.y, handle.transform.position.z);
            //처음 위치 설정 
            mario.transform.position = handle.transform.position;

            //핸들 이동하기 
            this.StartCoroutine(this.CoMoveHandle());
            this.StartCoroutine(this.CoMoveFlag());
            this.StartCoroutine(this.CoLoadGameOver());
            // mario.IgnoreInput(false);
        }


    }
    private IEnumerator CoMoveFlag()
    {
        while (true)
        {
            flagGo.transform.Translate(this.moveSpeed * Vector3.down * Time.deltaTime);
            if (flagGo.transform.localPosition.y <= 0.3f)
            {
                this.moveSpeed = 0f;
                this.audioSource.PlayOneShot(this.gameOverSfx);
                break;
            }
            yield return null;
        }
        Debug.LogFormat("깃발이 이동을 완료 했습니다.");
 

    }
    private IEnumerator CoLoadGameOver()
    {
        yield return new WaitForSeconds(3f);
        SceneManager.LoadScene("GameOverScene");
        
    }
    private IEnumerator CoMoveHandle()
    {
        while (true)
        {
            handle.transform.Translate(this.moveSpeed * Vector3.down * Time.deltaTime);
            if (handle.transform.localPosition.y <= 0.63f)
            {
                this.moveSpeed = 0f;
                break;
            }
            yield return null;
        }
        Debug.LogFormat("handle이 이동을 완료 했습니다.");
    }

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

public class Map1Main : MonoBehaviour
{
    private AudioSource audioSource;
    [SerializeField]
    private AudioClip backgoundSfx;
    [SerializeField]
    private UIDirector uiDirector;
    [SerializeField]
    private GameObject uiPrefab;
    private Transform parent;
    [SerializeField]
    private GameObject marioPrefab;
    [SerializeField]
    private Transform marioTrans;
    [SerializeField]
    private CameraController cameraController;

    private MarioController marioController;
    // Start is called before the first frame update

    void Start()
    {
        //오디오
        this.audioSource = this.GetComponent<AudioSource>();
        this.audioSource.PlayOneShot(this.backgoundSfx);

        DataManager.instance.LoadMarioData();
        //ui 생성--------------------------------------------
        GameObject uiGo = Instantiate(this.uiPrefab);
        uiGo.transform.SetParent(parent, false);
        this.uiDirector = uiGo.GetComponent<UIDirector>();
        this.uiDirector.UpdateUI();
        uiDirector.txtMapName.text = string.Format("WORLD\n1-1");
        //마리오 생성-----------------------------------------
        GameObject marioGo = Instantiate(marioPrefab);
        marioGo.transform.position = this.marioTrans.position;
        marioGo.name = "Mario";//Mario 이름으로 생성됨
        cameraController.Init();
        this.marioController = marioGo.GetComponent<MarioController>();

        this.marioController.onGetMushroom = (scale) => {
            this.marioController.Bigger(scale);//크기 증가하는 함수
            Debug.LogFormat("버섯획득 : isBig => {0}", this.marioController.IsBig);//true or false 출력
        };

        this.marioController.onAttackedEnemy = (scale) =>
        {
            this.marioController.Smaller(scale);
            Debug.Log("적과 부딪혔습니다.");
        };

        this.marioController.onChangeScene = (sceneName) => {
            this.ChangeScene(sceneName);//레이 검사해서 포탈 있으면 onChangeScene 호출하고 있음
        };

        this.marioController.onCoinEat = () =>
        {
            this.EatCoin();
            Debug.Log("코인획득");
        };
    }

    public void ChangeScene(string sceneName)
    {
        bool isBig = this.marioController.IsBig;//현재 씬에서 커진 상태 다음 씬담당 메인에게 전달
        bool isSmall = this.marioController.IsSmall;
        Debug.LogFormat("isBig: {0}", isBig);
        AsyncOperation asyncOperation = SceneManager.LoadSceneAsync(sceneName);
        //씬로드가 완료되면 호출 되는 이벤트에 대리자 연결 
        asyncOperation.completed += (obj) => {

            switch (sceneName)
            {
                //굴둑 동전 먹으러 
                case "Map2Scene":
                    //다음 씬 메인 가져오기 
                    Map2main map2Main = GameObject.FindObjectOfType<Map2main>();
                    if (isBig)
                    {
                        map2Main.InitBig(isBig);//초기화 //마리오 생성
                        //map2Main.InitUI();
                    }
                    else if (isSmall)
                    {
                        map2Main.InitSmall(isSmall);

                    }
                    else
                        map2Main.InitSmall(isSmall);
                    break;
            }

        };

    }
    private void Save()
    {

    }
    public void EatCoin()
    {
        Debug.Log("eatCoin 호출");
        uiDirector.IncreaseScore(50);
        uiDirector.IncreaseCoin();
        uiDirector.UpdateUI();
    }
   
}
using System.Collections;
using System.Collections.Generic;
using TMPro.Examples;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.SocialPlatforms.Impl;
using UnityEngine.UI;

public class Map2main : MonoBehaviour
{
    private AudioSource audioSource;
    [SerializeField]
    private AudioClip backgoundSfx;
    private UIDirector uiDirector;
    [SerializeField]
    private GameObject uiPrefab;
    private Transform parent;
    [SerializeField]
    private GameObject marioPrefab;
    [SerializeField]
    private Transform marioTrans;
    private MarioController marioController;
    
    void Start()
    {

        this.audioSource = this.GetComponent<AudioSource>();
        this.audioSource.PlayOneShot(this.backgoundSfx);
        uiDirector.UpdateUI();
        //this.LoadData();
        //this.txtMapName.text = string.Format("WORLD\n1-2");
        //this.time = PlayerPrefs.GetFloat("Time");
        ////uiGo.transform.SetParent(parent, false);
        ///GameObject uiGo = Instantiate(this.uiPrefab);
        this.marioController.onChangeScene = (sceneName) => {
            this.ChangeScene(sceneName);//레이 검사해서 포탈 있으면 onChangeScene 호출하고 있음
        };
        uiDirector.txtMapName.text = string.Format("WORLD\n1-2");
        this.marioController.onCoinEat = () =>
        {
            this.EatCoin();
            Debug.Log("코인획득");
        };
    }
    public void ChangeScene(string sceneName)
    {
        bool isBig = this.marioController.IsBig;   //현재 씬에서 커진 상태 다음 씬담당 메인에게 전달
        Debug.LogFormat("isBig: {0}", isBig);
        AsyncOperation asyncOperation = SceneManager.LoadSceneAsync(sceneName);
        //씬로드가 완료되면 호출 되는 이벤트에 대리자 연결 
        asyncOperation.completed += (obj) =>
        {

            switch (sceneName)
            {

                case "Map3Scene":
                    Map3main map3Main = GameObject.FindObjectOfType<Map3main>();
                    map3Main.Init(isBig);
                    break;
            }

        };

    }
    public void EatCoin()
    {
        Debug.Log("eatCoin 호출");
        uiDirector.IncreaseScore(50);
        uiDirector.IncreaseCoin();
        uiDirector.UpdateUI();
    }
    //public void InitUI()
    //{
    //   this.CreateUI();
    //}

    public void InitBig(bool isBig)
    {
        //마리오 만들기 
        this.CreateMarioBig(isBig);

        //UI생성 
        this.CreateUI(); ;
    }
    public void InitSmall(bool isSmall)
    {
        //마리오 만들기 
        this.CreateMarioSmall(isSmall);
        this.CreateUI();
    }

    // Update is called once per frame
    //void Update()
    //{
    //    this.time -= Time.deltaTime;
    //    this.txtTime.text = time.ToString("F0");
    //    this.txtTime.text = string.Format("TIME\n{0}", this.txtTime.text);
    //    this.SaveData();
    //}
    //public void LoadData()
    //{
    //    int score = PlayerPrefs.GetInt("Score");
    //    this.txtScore.text = score.ToString();
    //    this.txtScore.text = string.Format("MARIO\n{0:D6}", score);

    //    this.txtCoin.text= PlayerPrefs.GetInt("Coin").ToString();
    //    this.txtCoin.text = string.Format("X {0}", this.txtCoin.text);
    //}

    //public void SaveData()
    //{
    //    PlayerPrefs.SetInt("Score2", score);
    //    PlayerPrefs.SetFloat("Time2",time);
    //    PlayerPrefs.SetInt("Coin2", coin);
    //}

    private void CreateMarioBig(bool isBig)
    {
      
        var go = Instantiate(this.marioPrefab);
        go.transform.position = this.marioTrans.position;
        go.name = "Mario";
        this.marioController = go.GetComponent<MarioController>();

        //이전씬에서 커진 상태 전달 받아 크게 만들기 
        if (isBig)//이미 커진 상태일때 -> 생성할 때 크게 만들기
            this.marioController.Bigger(0.6f);
            
    }
    private void CreateMarioSmall(bool isSmall)
    {

        var go = Instantiate(this.marioPrefab);
        Debug.Log(go);
        go.transform.position = this.marioTrans.position;
        go.name = "Mario";
        this.marioController = go.GetComponent<MarioController>();

        //이전씬에서 작은 상태 전달 받아 작게 만들기 
        if (isSmall)//이미 작아진 상태일때 -> 생성할 때 작게 만들기
            this.marioController.Smaller(0.4f);

    }
    private void CreateUI()
    {
        GameObject uiGo = Instantiate(this.uiPrefab);
        uiGo.transform.SetParent(parent, false);
        this.uiDirector = uiGo.GetComponent<UIDirector>();
        this.uiDirector.LoadData();
    }
}
using System.Collections;
using System.Collections.Generic;
using TMPro.Examples;
using UnityEngine;
using UnityEngine.UI;

public class Map3main : MonoBehaviour
{
    private AudioSource audioSource;
    [SerializeField]
    private AudioClip backgoundSfx;
    [SerializeField]
    private GameObject uiPrefab;
    private Transform parent;
    private UIDirector uiDirector;
    [SerializeField]
    private GameObject marioPrefab;
    [SerializeField]
    private Transform marioTrans;
    private MarioController marioController;
    [SerializeField]
    private CameraController cameraController;
    // Start is called before the first frame update

    private void Start()
    {
        this.audioSource = this.GetComponent<AudioSource>();
        this.audioSource.PlayOneShot(this.backgoundSfx);
        this.marioController.onCoinEat = () =>
        {
            this.EatCoin();
            Debug.Log("코인획득");
        };
        uiDirector.txtMapName.text = string.Format("WORLD\n2-1");
    }
    public void EatCoin()
    {
        Debug.Log("eatCoin 호출");
        uiDirector.IncreaseScore(50);
        uiDirector.IncreaseCoin();
        uiDirector.UpdateUI();
    }
    public void Init(bool isBig)
    {
        //마리오 만들기 
        this.CreateMario(isBig);
        cameraController.Init();
        this.CreateUI();
    }


    private void CreateMario(bool isBig)
    {
        var go = Instantiate(marioPrefab);
        go.transform.position = this.marioTrans.position;
        go.name = "Mario";
        this.marioController = go.GetComponent<MarioController>();

        //이전씬에서 커진 상태 전달 받아 크게 만들기 
        if (isBig)//이미 커진 상태일때 -> 생성할 때 크게 만들기
            this.marioController.Bigger(0.6f);
 

    }
    private void CreateUI()
    {
        GameObject uiGo = Instantiate(this.uiPrefab);
        uiGo.transform.SetParent(parent, false);
        this.uiDirector = uiGo.GetComponent<UIDirector>();
        this.uiDirector.LoadData();
    }
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Unity.VisualScripting;
using Unity.VisualScripting.Antlr3.Runtime.Tree;
using UnityEditor.Experimental.GraphView;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class MarioController : MonoBehaviour
{
    private AudioSource audioSource;
    [SerializeField]
    private AudioClip eatCoinSfx;
    [SerializeField]
    private AudioClip powerUpSfx;
    [SerializeField]
    private AudioClip portalSfx;
    [SerializeField]
    private AudioClip jumpSfx;
    private Rigidbody2D rBody2D;
    public float jumpForce = 500f;
    public float moveForce = 60f;
    public Animator anim;
    private bool isJump = false;
    private bool isLongJump = false;
    //[SerializeField]
    //private UIDirector uiDirector;
    [SerializeField]
    private Transform rayOrigin;    //체크 아래쪽 하기 위한 레이 발사 시작 위치 
    //private float scaleChange = 0;

    public System.Action<float> onGetMushroom; //대리자 변수 정의 
    public System.Action<float> onAttackedEnemy;
    public System.Action<string> onChangeScene;
    public System.Action onCoinEat;

    // Start is called before the first frame update
    void Start()
    {
        this.audioSource = this.GetComponent<AudioSource>();
        this.rBody2D = this.GetComponent<Rigidbody2D>();
        this.anim = this.GetComponent<Animator>();
       
    }

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

        //인풋이 막인 상태에서는 아무것도 못하게 막음 
        if (this.ignoreInput) return;
        
        //jump
        if (Input.GetKeyDown(KeyCode.Space))
        {
            // 이중점프 막기
            if (this.rBody2D.velocity.y == 0)
            {
                this.rBody2D.AddForce(Vector2.up * this.jumpForce);
                if (this.isJump == false)
                {
                    this.isJump = true;
                }
                this.audioSource.PlayOneShot(this.jumpSfx);
            }
        }
        if (this.isJump)
        {
            if (this.rBody2D.velocity.y > 0)
            {
                // Jumping
                this.anim.SetBool("isJump", true);
            }
            else if (this.rBody2D.velocity.y <= 0)
            {
                // Falling
                this.anim.SetBool("isJump", false);
            }
        }
        //if (Input.GetButtonUp("Horizontal"))
        //{
        //    this.rBody2D.velocity = new Vector2(this.rBody2D.velocity.normalized.x * 0.8f, this.rBody2D.velocity.y);
        //}
        //if (this.isJump)// space를 눌렀는데 
        //{
        //if (this.rBody2D.velocity.y > 0)// 점프상태
        //{
        // this.anim.SetInteger("State", 2);
        //}
        //}

        int dirX = 0;


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

        if (Input.GetKey(KeyCode.RightArrow))
        {
            dirX = 1;
        }
        float speedX = Mathf.Abs(this.rBody2D.velocity.x);//절대값(속도는 음수 나오면 안됨), 가속도

        if (speedX < 5f)//가속도 제한 
        {
            this.rBody2D.AddForce(new Vector2(dirX, 0) * this.moveForce);
        }

        //움직이는 방향으로 쳐다보기 
        if (dirX != 0)//달리고 있다면?
        {
            //if (!this.isJump)//좌우를 쳐다보는데 점프 상태가 아니라면 => 걷는중
            //{
                this.anim.SetInteger("State", 1);
                this.anim.SetBool("isJump", false);
            //}
            this.transform.localScale = new Vector3(dirX *Mathf.Abs(this.transform.localScale.x), this.transform.localScale.y, 1);
            this.transform.position = new Vector3(Mathf.Clamp(this.transform.position.x, -8.1f, 25.9f),this.transform.position.y, 0);
        
        }
        else//좌우를 쳐다보지도 않고 점프 상태도 아니라면 =>idle
        {
            if (this.isJump==false)
            {
                this.anim.SetInteger("State", 0);
                this.anim.SetBool("isJump", false);
            }
        }
        this.anim.speed = speedX / 2.0f;

        //길게 누르면 높은 점프 짧게 누르면 낮은 점프
        if (Input.GetKey(KeyCode.Space))
        {
            isLongJump = true;
        }
        else if (Input.GetKeyUp(KeyCode.Space))
        {
            isLongJump = false;
        }



        if (Input.GetKeyDown(KeyCode.DownArrow))
        {
            Debug.Log("아래 들어갈때가 있는지 확인한다");
            this.CheckPortalBelow();
        }
        if (Input.GetKeyDown(KeyCode.RightArrow))
        {
            this.CheckPortalRight();
        }

    }

    private Coroutine routineCheckPortalBelow;
    private Coroutine routineCheckPortalRight;
    private void CheckPortalBelow()
    {
        if (this.routineCheckPortalBelow != null) StopCoroutine(this.routineCheckPortalBelow);
        this.routineCheckPortalBelow = this.StartCoroutine(this.CoCheckPortalBelow());
    }
    private void CheckPortalRight()
    {
        if (this.routineCheckPortalRight != null) StopCoroutine(this.routineCheckPortalRight);
        this.routineCheckPortalRight = this.StartCoroutine(this.CoCheckPortalRight());
    }

    private IEnumerator CoCheckPortalBelow()
    {
        yield return null;


        //레이를 만듬 
        Ray ray = new Ray(this.rayOrigin.transform.position, this.transform.up * -1);//this.transform.up*-1 = 아래로 레이만들기
        
        Debug.DrawRay(ray.origin, ray.direction, Color.red, 10f);
        

        LayerMask mask = 1 << LayerMask.NameToLayer("Mario");//마리오Layer만(6)
        RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, 1, ~mask);//~mask= 마리오 빼고 다
        
        if (hit)
        {
            Debug.Log(hit.collider.gameObject.name);
            if (hit.collider.gameObject.name == "portal2")
            {
                Debug.Log("씬2로 전환");
                this.onChangeScene("Map2Scene");
                this.audioSource.PlayOneShot(this.portalSfx);
            }
        }
        

    }
    private IEnumerator CoCheckPortalRight()
    {
        yield return null;

        Ray ray2 = new Ray(this.rayOrigin.transform.position, this.transform.right * -1);
        Debug.DrawRay(ray2.origin, ray2.direction, Color.green, 12f);
        LayerMask mask = 1 << LayerMask.NameToLayer("Mario");//마리오Layer만(6)
        RaycastHit2D hit2 = Physics2D.Raycast(ray2.origin, ray2.direction, 1, ~mask);

        if (hit2)
        {
            Debug.Log(hit2.collider.gameObject.name);
            if (hit2.collider.gameObject.name == "portal3")
            {
                Debug.Log("씬3으로전환");
                this.onChangeScene("Map3Scene");
                this.audioSource.PlayOneShot(this.portalSfx);
            }
            
        }

    }
    private void FixedUpdate()
    {
        //인풋이 막인 상태에서는 아무것도 안함 
        if (this.ignoreInput) return;

        if (isLongJump && this.rBody2D.velocity.y > 0)
        {
            this.rBody2D.gravityScale = 1.2f;
        }
        else
        {
            this.rBody2D.gravityScale = 2.5f;
        }

    }

    private void OnTriggerStay2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "flag")
        { 
            this.anim.SetInteger("State", 3);

        }
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.tag == "coin")
        {
            Destroy(other.gameObject);
            this.onCoinEat();
            this.audioSource.PlayOneShot(this.eatCoinSfx);
        }
            //this.uiDirector.IncreaseScore(400);

        
        //this.uiDirector.UpdateUI();

    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        
        if (collision.gameObject.tag == "mushroom")
        {
            Destroy(collision.gameObject);  //버섯 제거 
            this.audioSource.PlayOneShot(this.powerUpSfx);
            this.onGetMushroom(0.6f);    //대리자 호출 

        }

        //if (isSmall == false)
        //{
        if (collision.gameObject.tag == "enemy")
        {
            //if (this.transform.localScale.x == 0.4f)
            //{
            //    SceneManager.LoadScene("GameOverScene");
            //}
            //this.onAttackedEnemy(0.4f);
            //Destroy(collision.gameObject);
        }
        //}
    }


    public void Bigger(float scale)
    {
        if (this.IsBig)
        {
            Debug.Log("이미 커진 상태 입니다.");
        }
        else //작은 상태면 크기증가
        {
            this.transform.localScale = new Vector3(0.6f, 0.6f, 0.6f);
            this.IsBig = true;
        }
        
    }
    public void Smaller(float scale)
    {
        if (this.IsSmall)
        {
            Debug.Log("이미 작아진 상태 입니다.");
        }
        else
        {
            this.transform.localScale = new Vector3(0.4f, 0.4f, 0.4f);
            this.IsSmall = true;
            this.IsBig = false;
        }
        
    }

    private bool ignoreInput = false;
    public void IgnoreInput(bool ignore)
    {
        ignoreInput = ignore;
        Debug.LogFormat("IgnoreInput: <color=lime>{0}</color>", this.ignoreInput);
    }

    public bool IsBig//true,false
    {
        get; set;
    }
    public bool IsSmall
    {
        get;set;
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MarioData
{
    public int id;
    public int score;
    public int time;
    public int coin_amount;
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MushroomController : MonoBehaviour
{
    public float moveSpeed = 0.05f;
    private Animator anim;
    //private MarioController marioController;

    void Start()
    {
        this.anim = this.GetComponent<Animator>();
    }
    // Update is called once per frame
    void Update()
    {
        this.transform.Translate(this.moveSpeed, 0, 0);
        if (this.transform.position.y < -3.5f)
        {
            Destroy(this.gameObject);
        }
    }
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "portal")
        {
            moveSpeed = moveSpeed * -1;
        }
        if (collision.gameObject.tag == "wall")
        {
            moveSpeed = moveSpeed * -1;
        }
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "mario")
        {
            //애니메이션 실행
            this.anim.SetBool("isAttacked", true);
            this.transform.position = new Vector3(this.transform.position.x, this.transform.position.y - 0.3f);//-2.69-(-3.16)
            this.moveSpeed = 0f;
            //몇초후 사라지기
            Invoke("Die", 0.15f); 
        }
    }
    private void Die()
    {
        Destroy(this.gameObject);
    }
}
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UI;

public class UIDirector : MonoBehaviour
{
    
    [SerializeField]
    private Text txtScore;
    [SerializeField]
    private Text txtCoin;
    [SerializeField]
    private Text txtTime;
    public Text txtMapName;

    public float time =400f;
    private int score=0;
    private int coin=0;
    // Start is called before the first frame update
    void Start()
    {
        //this.LoadData();
        //this.txtMapName.text = string.Format("WORLD\n1-1");
        //this.UpdateUI();
        //PlayerPrefs.SetInt
    }

    // Update is called once per frame
    void Update()
    {
        this.time -= Time.deltaTime;
        this.txtTime.text = this.time.ToString("F0");//정수로 표현
        this.txtTime.text = string.Format("TIME\n{0}", this.txtTime.text);
    }

    public void UpdateUI()
    {
        List<MarioData> marioDatas = DataManager.instance.GetMarioDatas();
        foreach (MarioData data in marioDatas) {
            Debug.LogFormat("<color=green>id:{0},score{1}</color>",data.id,data.score);
        }
        this.txtScore.text = string.Format("MARIO\n{0:D6}", score);//총 6자리로 앞에 0으로 채우기
        this.txtCoin.text = string.Format("X {0}", this.coin);
        this.SaveData();
    }
    public void IncreaseScore(int score)
    {
        Debug.Log("50점 획득");
        this.score += score;
    }
    public void IncreaseCoin()
    {
        this.coin += 1;
    }

    public void SaveData()
    {
        
        PlayerPrefs.SetInt("Score",score);
        PlayerPrefs.SetFloat("Time", time);
        PlayerPrefs.SetInt("Coin", coin);
    }
    public void LoadData()
    {
        int score = PlayerPrefs.GetInt("Score");
        this.txtScore.text = score.ToString();
        this.txtScore.text = string.Format("MARIO\n{0:D6}", score);

        this.txtCoin.text = PlayerPrefs.GetInt("Coin").ToString();
        this.txtCoin.text = string.Format("X {0}", this.txtCoin.text);
    }
}

'2D 콘텐츠 제작 개발일지 (mario)' 카테고리의 다른 글

마리오 개발 보완하기  (1) 2024.09.25
유니티(unity) 씬 전환 시 UI 유지하기  (3) 2024.09.25
마리오 개발 8일차  (0) 2023.09.20
마리오 개발 7일차  (2) 2023.09.19
마리오 개발 6일차  (0) 2023.09.18