Unity-자동차 스와이프 예제2-UI, 사운드추가
-UI 요소는 캔버스 안에 존재한다.
-EventSystem을 지우면 UI와 사용자 인터렉션이 불가능하다. ex) 버튼이 안눌린다
Rect Transform 은 Transform을 상속받는다.
https://www.techiedelight.com/ko/round-float-to-2-decimal-points-csharp/
gameDirector 오브젝트를 만들어 GameDirector 스크립트를 넣어준다.
소수점 이하 2자리로 반올림을 하기 위해 ToString()을 사용하였다.
게임오브젝트 distanceGo의 Text컴포넌트를 text 변수에 저장하여 텍스트 내용을 바꾸어준다.
+)Text를 사용하려면 using UnityEngine.UI를 추가해야한다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameDirector : MonoBehaviour
{
GameObject carGo;
GameObject flagGo;
GameObject distanceGo;
// Start is called before the first frame update
void Start()
{
//자동차
this.carGo = GameObject.Find("car");
//깃발
this.flagGo = GameObject.Find("flag");
//UI
this.distanceGo = GameObject.Find("Distance");
Debug.LogFormat("car: {0}",this.carGo);
Debug.LogFormat("flag: {0}", this.flagGo);
Debug.LogFormat("distance: {0}", this.distanceGo);
}
// Update is called once per frame
void Update()
{
//매프레임마다 자동차와 깃발의 거리를 계산해 UI에 출력해야함
//거리 = 목표위치 - 시작위치
float distanceX = this.flagGo.transform.position.x - this.carGo.transform.position.x;
Debug.LogFormat("distanceX: {0}", distanceX);
Text text = distanceGo.GetComponent<Text>();
text.text = string.Format("목표지점까지 거리 {0}m", distanceX).ToString();
if (distanceX <=0)
{
text.text = "GameOver";
}
}
}
사운드 추가하기
-오디오 소스, 오디오 클립이 필요하다.
-오디오 소스에서 오디오 클립을 실행한다.
오디오 소스 인스턴스를 오디오 클립 변수에 할당(값을 할당)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameDirector : MonoBehaviour
{
GameObject carGo;
GameObject flagGo;
GameObject distanceGo;
bool isGameOver = false;
// Start is called before the first frame update
void Start()
{
//자동차
this.carGo = GameObject.Find("car");
//깃발
this.flagGo = GameObject.Find("flag");
//UI
this.distanceGo = GameObject.Find("Distance");
Debug.LogFormat("car: {0}",this.carGo);
Debug.LogFormat("flag: {0}", this.flagGo);
Debug.LogFormat("distance: {0}", this.distanceGo);
}
// Update is called once per frame
void Update()
{
//매프레임마다 자동차와 깃발의 거리를 계산해 UI에 출력해야함
//거리 = 목표위치 - 시작위치
float distanceX = this.flagGo.transform.position.x - this.carGo.transform.position.x;
// Debug.LogFormat("distanceX: {0}", distanceX);
Text text = distanceGo.GetComponent<Text>();
text.text = string.Format("목표지점까지 거리 {0}m", distanceX).ToString();
if (distanceX <=0)
{
text.text = "GameOver";
CarController carController = this.carGo.GetComponent<CarController>();
//CarController의 컴포넌트 가져옴
if(isGameOver == false)
{
carController.PlayLoseSound();
isGameOver = true;
}
}
}
}
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UIElements;
public class CarController : MonoBehaviour
{
public float x;
public float y;
public float z;
float dampingCoefficient = 0.96f;//감쇠계수
public AudioClip[] audioClips;
Vector3 startPos;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
startPos = Input.mousePosition;
Debug.LogFormat("Down: {0}", startPos);//A
//움직이기-위치 정보 변함
//원점으로 게임 오브젝트 이동
Debug.Log(this);//CarController 클래스의 인스턴스
Debug.Log(this.gameObject);//CarController 컴포넌틑가 붙어있는 게임 오브젝트 Instance
//구조체의 멤버 싱글로 할당 불가
//따라서 Vector3는 구조체이므로 모두 채워줘야함
// x = 0.5f;
// this.gameObject.transform.position += new Vector3 (x,y,z);
this.x = 0.2f;
}
else if (Input.GetMouseButtonUp(0))//B
{
Debug.LogFormat("Up: {0}", Input.mousePosition);
Vector3 endPos = Input.mousePosition;
float swipeLength = endPos.x - this.startPos.x;//B.x - A.x : x좌표의 거리
this.x = swipeLength*0.0005f;//world좌표계와 local 좌표계를 맞춰주기 위해서
//화면 좌표계의 거리에 비례해서 이동(mousPosition은 world이므로)
PlayMoveSound();
}
this.transform.Translate(this.x, this.y, this.z);
this.x *= dampingCoefficient;//속도가 점점 느려진다.
}
public void PlayMoveSound()
{
//오디오 실행
AudioSource audio = this.gameObject.GetComponent<AudioSource>();
// audio.Play();
AudioClip audioclip = this.audioClips[0];
audio.PlayOneShot(audioclip);
}
public void PlayLoseSound()
{
//오디오 실행
AudioSource audio = this.gameObject.GetComponent<AudioSource>();
AudioClip audioclip = this.audioClips[1];
audio.PlayOneShot(audioclip);
}
}
'유니티 기초' 카테고리의 다른 글
Unity-Prefab, 예제-랜덤한 위치에 화살생성, hp게이지 만들기 (0) | 2023.08.02 |
---|---|
Unity-Player Setting에서 Deafult Orientaiton (0) | 2023.08.02 |
Unity- CatEscape 예제, time (0) | 2023.08.01 |
Unity- 자동차 스와이프 예제 (0) | 2023.08.01 |
HelloWorld-Unity 기본, life Cycle, 룰렛 프로젝트 (0) | 2023.07.31 |