오늘 할 일
오전
씬 2->씬 3 마리오 넘기기
적 위에서 아래로 밟으면 적 죽기
오후
UI 옮기기
1. 씬2->씬 3 마리오 넘기기
using System.Collections;
using System.Collections.Generic;
using TMPro.Examples;
using UnityEngine;
using UnityEngine.UI;
public class Map3main : MonoBehaviour
{
[SerializeField]
private GameObject marioPrefab;
[SerializeField]
private Transform marioTrans;
private MarioController marioController;
[SerializeField]
private CameraController cameraController;
// Start is called before the first frame update
public void Init(bool isBig)
{
//마리오 만들기
this.CreateMario(isBig);
cameraController.Init();
}
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);
//else
}
}
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
{
//[SerializeField]
//private Text txtScore;
//[SerializeField]
//private Text txtCoin;
//[SerializeField]
//private Text txtTime;
//[SerializeField]
//private Text txtMapName;
//private int score;
//private int coin;
//private float time;
[SerializeField]
private GameObject uiPrefab;
private Transform parent;
[SerializeField]
private GameObject marioPrefab;
[SerializeField]
private Transform marioTrans;
private MarioController marioController;
void Start()
{
//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 호출하고 있음
};
}
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 Init(bool isBig)
{
//마리오 만들기
this.CreateMario(isBig);
//UI생성
GameObject uiGo = Instantiate(this.uiPrefab);
uiGo.transform.SetParent(parent, false);
}
// 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 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);
//else
}
}
<MarioController>
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, 10f);
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");
}
}
}
if (Input.GetKeyDown(KeyCode.RightArrow))
{
Debug.Log("오른쪽 들어갈데가 있는지 확인한다");
this.CheckPortalRight();
}
}
private Coroutine routineCheckPortalRight;
private void CheckPortalRight()
{
if (this.routineCheckPortalRight != null) StopCoroutine(this.routineCheckPortalRight);
this.routineCheckPortalRight = this.StartCoroutine(this.CoCheckPortalRight());
}
계속 씬 전환이 되지 않아서 애먹었었는데 portal3이름에 작은 따옴표를 찍어서 안되던것이었다;
문제점1. 크기가 커진 상태-> 커진 상태, 작은상태 -> 작은상태는 잘 되는데
버섯을 먹어서 커졌다가 적을 만나 작아진 상태-> 커진상태 로 잘못 표시된다.
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 Rigidbody2D rBody2D;
private float jumpForce = 500f;
private float moveForce = 60f;
private 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;
// Start is called before the first frame update
void Start()
{
this.rBody2D = this.GetComponent<Rigidbody2D>();
this.anim = this.GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
//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;
}
}
}
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");
}
}
}
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, 10f);
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");
}
}
}
private void FixedUpdate()
{
if (isLongJump && this.rBody2D.velocity.y > 0)
{
this.rBody2D.gravityScale = 1.2f;
}
else
{
this.rBody2D.gravityScale = 2.5f;
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "coin")
{
Destroy(other.gameObject);
//this.main1.EatCoin();
//this.uiDirector.IncreaseScore(50);
//this.uiDirector.IncreaseCoin();
}
else if (other.gameObject.tag == "flag")
{
//this.uiDirector.IncreaseScore(400);
}
else if (other.gameObject.tag == "castle")
{
//this.uiDirector.time = 0;
//코루틴 하면 좋을거같음
//SceneManager.LoadScene("GameOverScene");
}
//this.uiDirector.UpdateUI();
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "mushroom")
{
Destroy(collision.gameObject); //버섯 제거
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);
}
//}
}
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;
}
}
public bool IsBig//true,false
{
get; set;
}
public bool IsSmall
{
get;set;
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UIElements;
public class Map1Main : MonoBehaviour
{
[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()
{
GameObject uiGo = Instantiate(this.uiPrefab);
uiGo.transform.SetParent(parent, false);
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 호출하고 있음
};
}
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);//초기화 //마리오 생성
}
else if (isSmall)
{
map2Main.InitSmall(isSmall);
}
break;
}
};
}
}
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
{
[SerializeField]
private GameObject uiPrefab;
private Transform parent;
[SerializeField]
private GameObject marioPrefab;
[SerializeField]
private Transform marioTrans;
private MarioController marioController;
void Start()
{
//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 호출하고 있음
};
}
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 InitBig(bool isBig)
{
//마리오 만들기
this.CreateMarioBig(isBig);
//UI생성
GameObject uiGo = Instantiate(this.uiPrefab);
uiGo.transform.SetParent(parent, false);
}
public void InitSmall(bool isSmall)
{
//마리오 만들기
this.CreateMarioSmall(isSmall);
//UI생성
GameObject uiGo = Instantiate(this.uiPrefab);
uiGo.transform.SetParent(parent, false);
}
private void CreateMarioBig(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 CreateMarioSmall(bool isSmall)
{
var go = Instantiate(marioPrefab);
go.transform.position = this.marioTrans.position;
go.name = "Mario";
this.marioController = go.GetComponent<MarioController>();
//이전씬에서 작은 상태 전달 받아 작게 만들기
if (isSmall)//이미 작아진 상태일때 -> 생성할 때 작게 만들기
this.marioController.Smaller(0.4f);
}
}
2. 적 위에서 아래로 밟으면 적 사라지기
이것도 ray를 쏘는게 나을지 collider하는게 나을지
죽는 애니메이션을 위치로 설정했더니(눌리면 위치를 아래쪽으로 움직이고 싶어서) 움직이지 않음
흠 그러면 죽는거 애니메이션 하고 공중에 찌그러지는 느낌을 어떻게 안줘야할까 ..
=> 코드 상으로 y값의 위치를 변경하고 , collider의 y 값을 줄이기(자동으로 줄어든다, box collider 일 때)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MushroomController : MonoBehaviour
{
public float moveSpeed = 0.05f;
private Animator anim;
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.29f);//-2.69-(-3.16)
this.moveSpeed = 0f;
//몇초후 사라지기
Invoke("Die", 1f);
}
}
private void Die()
{
Destroy(this.gameObject);
}
}
퀄리티 높히기 -> 마리오 약간 튕기기
문제점 부딪혀서 크기도 작아져버림
모서리에 있을때 이상한거 해결하기 ( 점프 애니메이션이 실행됨)
ui 유지하기
map 1에서 동적으로 생성하고 코인 먹으면 점수 증가
처음에 코인이 증가하지 않음 -> ui Director를 생성된 uiprefab의 uiDirector를 변경한게 아니어서 안됨
GameObject uiGo = Instantiate(this.uiPrefab);
uiGo.transform.SetParent(parent, false);
this.uiDirector = uiGo.GetComponent<UIDirector>();
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UIElements;
public class Map1Main : MonoBehaviour
{
[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()
{
//ui 생성--------------------------------------------
GameObject uiGo = Instantiate(this.uiPrefab);
uiGo.transform.SetParent(parent, false);
this.uiDirector = uiGo.GetComponent<UIDirector>();
//마리오 생성-----------------------------------------
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;
}
};
}
public void EatCoin()
{
Debug.Log("eatCoin 호출");
uiDirector.IncreaseScore(50);
uiDirector.IncreaseCoin();
uiDirector.UpdateUI();
}
}
marioController에 추가
public System.Action onCoinEat;
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "coin")
{
Destroy(other.gameObject);
this.onCoinEat();
}
using System.Collections;
using System.Collections.Generic;
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()
{
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);
}
}
saveData. LoadData를 이용하니가 다음 씬에서도 불러와지긴 하는데 유니티 실행을 껐다가 켜도 계속 남아있고 , 시간은 저장안됨-> 씬이 변환될때 LoadData를 호출함
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 UIDirector uiDirector;
[SerializeField]
private GameObject uiPrefab;
private Transform parent;
[SerializeField]
private GameObject marioPrefab;
[SerializeField]
private Transform marioTrans;
private MarioController marioController;
void Start()
{
//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 호출하고 있음
};
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
{
[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.marioController.onCoinEat = () =>
{
this.EatCoin();
Debug.Log("코인획득");
};
}
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.Collections;
using System.Collections.Generic;
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()
{
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);
}
}
문제점1. 씬 전환되면 점수가 불러와지긴 하는데 그 점수에서 더 더하는게 아니라 새로 0부터 점수 올라감
문제점2. 시간이랑 맵 이름 여전히 변경 X
맵은 변경
using System.Collections;
using System.Collections.Generic;
using TMPro.Examples;
using UnityEngine;
using UnityEngine.UI;
public class Map3main : MonoBehaviour
{
[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.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();
}
}
집가서 깃발타는거, 성 도착하면 gameover 씬 나오기 ,모서리에서 이상한거 고치기, 적 밟기
내일 ui 하루종일 하고 시간남으면 효과음 넣기
1. 깃발 타기
모서리 이상한거
자세히 보니 기본 걷는 점프 애니메이션이 빠르게 변경되고 있음 코드상 문제인것같기도 하다
'2D 콘텐츠 제작 개발일지 (mario)' 카테고리의 다른 글
슈퍼마리오 전체코드 (1) | 2023.09.21 |
---|---|
마리오 개발 8일차 (0) | 2023.09.20 |
마리오 개발 6일차 (0) | 2023.09.18 |
마리오개발 5일차 (0) | 2023.09.17 |
마리오개발 4일차 (0) | 2023.09.16 |