Unity-자동차 스와이프 예제2-UI, 사운드추가
2023. 8. 1.

-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를 추가해야한다.

 

C#에서 float를 소수점 이하 2자리로 반올림

이 게시물에서는 C#에서 float를 소수점 이하 2자리로 반올림하는 방법에 대해 설명합니다. 1. 사용 ToString() 방법 우리는 사용할 수 있습니다 ToString() 부동 소수점 값을 일부 소수 자릿수로 형식화

www.techiedelight.com

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";
        }
    }
}

 

 

사운드 추가하기

-오디오 소스, 오디오 클립이 필요하다.

-오디오 소스에서 오디오 클립을 실행한다.

 

car.cs에 오디오 실행 코드 추가

오디오 소스 인스턴스를 오디오 클립 변수에 할당(값을 할당)

 

Play On Awake 체크가 해제되어야 원할때만 소리가난다.

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);
    }
}

myoskin