바스켓 컨트롤러
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class BasketController : MonoBehaviour
{
private GameData gameData; //게임데이터 저장소 연결
[SerializeField] private AudioClip appleSE;
[SerializeField] private AudioClip bombSE;
AudioSource audioSource;
public float score { get; set; } //속성 ; 외부 접근 가능 ; //점수
public float apple { get; set; } //속성 ; 외부 접근 가능 ; //사과갯수
public float bomb { get; set; } //속성 ; 외부 접근 가능 ; //폭탄갯수
public System.Action onHit; //대리자-> 게임저장소로 호출되는 값
private void Start()
{
this.audioSource = this.GetComponent<AudioSource>();
this.score = 0; //시작 초기화
this.apple = 0;
this.bomb = 0;
}
void Update()
{
//화면을 클릭하면 레이를 발사
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
//레이 속성
//ray.origin 시작위치
// ray.direction 방향
Debug.DrawRay(ray.origin, ray.direction * 20f, Color.red, 10);
//레이와 콜라이더의 충돌체크
RaycastHit hit; // 충돌지점
if (Physics.Raycast(ray.origin, ray.direction, out hit, 20))
{
//Debug.Log("충돌함");
//Debug.LogFormat("충돌지점={0}", hit.point);
int x = Mathf.RoundToInt(hit.point.x); //칸의 중심으로 좌표 설정
int z = Mathf.RoundToInt(hit.point.z);
this.transform.position= new Vector3(x, 0, z); //바구니 이동
}
}
}
private void OnTriggerEnter(Collider other) //아이템과 충돌시
{
Debug.LogFormat("{0}", other.gameObject.tag);
if (other.gameObject.tag == "Apple") //아이템 태그 지정
{
this.score += 20f;
this.apple += 1;
this.audioSource.PlayOneShot(this.appleSE);
}
else if (other.gameObject.tag == "Bomb")
{
this.score -= 10f;
this.bomb += 1;
this.audioSource.PlayOneShot(this.bombSE);
}
this.onHit(); //대리자 호출
Destroy(other.gameObject);
}
}
아이템 프리팹 만들기
- 사과 , 폭탄 둘다 아이템 컨트롤러 스크립트 지정해줌
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ItemController : MonoBehaviour
{
[SerializeField] float speed = 3f; //아이템 이동속도
void Update()
{
this.transform.Translate(Vector3.down * speed*Time.deltaTime); //아래로 방향이동
//바닥에 닿으면 제거
if (this.transform.position.y<=0)
{
Destroy(this.gameObject);
}
}
}
아이템 제너레이션 - 반복 생성 스크립트
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AppleItemGenerator : MonoBehaviour
{
[SerializeField] GameObject apple;
[SerializeField] GameObject bomb;
private float delta;
void Update()
{
delta += Time.deltaTime;
if (delta > 1)
{
delta = 0;
GameObject item; //게임오브젝트 apple, bomb
int dice = Random.Range(1, 3); //1 ~ 2 사이 랜덤값
if (dice == 1)
{
item = Instantiate(apple); // 1이 나왔을때 apple을 생성한다
}
else
{
item = Instantiate(bomb); // 나머지일때 bomb을 생성한다.
}
float x = Random.Range(-1, 1); // 랜덤한 x축의 범위
float z = Random.Range(-1, 1); // 랜덤한 z축의 범위
item.transform.position = new Vector3(x, 3, z);
}
}
}
게임 디렉터 : 게임 UI 연결
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class ApplecatchGameDirector : MonoBehaviour
{
[SerializeField] private GameObject basket;
[SerializeField] private GameData gameData; // 게임데이터 저장-> 씬전환할때 유지
[SerializeField] private Text scoreText;
[SerializeField] private Text timeText;
private float timeLeft = 30f; //제한시간 30초
void Start()
{
this.NextDoor(); //게임데이터에 저장
Invoke("ChangeScene", this.timeLeft); // 씬 전환 , 지연시간
}
private void NextDoor() // 바스켓 컨트롤러 호출
{
GameObject basketGo = this.basket;
BasketController basketController = basketGo.GetComponent<BasketController>();
basketController.onHit = () =>
{
this.gameData.UpdateData(basketController.score, basketController.apple, basketController.bomb);
this.scoreText.text = string.Format("점수 {0}",basketController.score);
};
}
void Update()
{
TimeAttack(); // 타이머 텍스트 적용
}
public void TimeAttack()
{
if (this.timeLeft > 0f)
{
this.timeLeft -= Time.deltaTime;
string minutes = Mathf.Floor(timeLeft / 60).ToString("00");
string seconds = Mathf.Floor(timeLeft % 60).ToString("00");
this.timeText.text = "남은시간 " + minutes + ":" + seconds;
}
}
}
void ChangeScene()
{
Debug.LogFormat("{0}{1}{2}",gameData.score,gameData.apple,gameData.bomb);
// 엔딩씬으로 전환
SceneManager.LoadScene("AppleEnd");
}
}
게임 데이터 씬 전환시 기억하기
게임데이터 매니저
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class GameData : MonoBehaviour //게임데이터 저장후 씬전환후 테이터 호출
{
public float score=0; //점수
public float apple=0; //사과갯수
public float bomb = 0; //폭탄갯수
private void Awake()
{
DontDestroyOnLoad(this.gameObject); //씬전환시 데이터 기억하기
}
public void UpdateData(float score, float apple, float bomb)
{
this.score = score;
this.apple = apple;
this.bomb = bomb;
}
public float GetScore()
{
return this.score;
}
public float GetApple()
{
return this.apple;
}
public float GetBomb()
{
return this.bomb;
}
}
게임 엔딩 씬 전환
엔딩씬 디렉터
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class EndSceneGenerator : MonoBehaviour
{
private GameData gameData; //게임데이터 호출
private float apple;
private float bomb;
private float score;
public Text textApple;
public Text textBomb;
public Text textScore;
public Button btnLoadScene; //게임 재시작 버튼
void Start()
{
this.gameData = GameObject.FindFirstObjectByType<GameData>();
this.score = this.gameData.score;
this.apple = this.gameData.apple;
this.bomb = this.gameData.bomb;
Debug.LogFormat("{0}{1}{2}", gameData.score, gameData.apple, gameData.bomb);
this.btnLoadScene.onClick.AddListener(() =>
{
SceneManager.LoadScene("AppleCatch"); //씬전환
}); //람다식
}
void Update()
{
this.textScore.text = string.Format("총 점수 : {0}",this.score);
this.textApple.text = string.Format("사과 갯수 : {0}", this.apple);
this.textBomb.text = string.Format("폭탄 갯수 : {0}",this.bomb);
}
}
'게임개발 > 게임 클라이언트 프로그래밍' 카테고리의 다른 글
ShootingSpace 진행 목록 (0) | 2024.03.05 |
---|---|
AppleCatch(3) 오류 해결 (1) | 2024.02.07 |
Hero : 씬 전환 데이터 가져오기 (0) | 2024.02.05 |
AppleCatch (1) (1) | 2024.02.05 |
ShootingSpace (5) 배경 스크롤링 (0) | 2024.02.04 |