유니티 기초/복습

자동차 스와이프 Swipe Car - 복습

다모아 2023. 8. 2. 00:46

GameDirector

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class GameDirector : MonoBehaviour
{
    GameObject carGo;
    GameObject flagGo;
    GameObject distanceGo;

    private bool isGameOver = false;

    // Start is called before the first frame update
    void Start()
    {
        this.carGo = GameObject.Find("car");
        this.flagGo = GameObject.Find("flag");
        this.distanceGo = GameObject.Find("Distance");

        Debug.LogFormat("carGo: {0}", this.carGo);
        Debug.LogFormat("flagGo: {0}", this.flagGo);
        Debug.LogFormat("distanceGo: {0}", this.distanceGo);
    }

    // Update is called once per frame
    void Update()
    {
        float distanceX = this.flagGo.transform.position.x - this.carGo.transform.position.x;
        Text text = this.distanceGo.GetComponent<Text>();

        if(distanceX >= flagGo.transform.position.z)
        {
            text.text = string.Format("목표지점까지의 거리: {0:0.00}m", distanceX);
        }
        else
        {
            text.text = string.Format("게임오버");
            if(isGameOver == false)
            {
                CarController carController = this.carGo.GetComponent<CarController>();
                carController.PlayLoseSound();
                isGameOver = true;
            }
        }

        

    }
}

 

CarController

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

public class CarController : MonoBehaviour
{
    public float moveSpeed;
    private float dampingCoeffient = 0.96f;

    public AudioClip[] audioClips;
    private float startPos;
    private float endPos;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
        //왼쪽 마우스 클릭시
        if(Input.GetMouseButtonDown(0))
        {
            //위치
            this.startPos = Input.mousePosition.x;
            Debug.LogFormat("startPos: {0}", startPos);
        }
        //왼쪽 마우스 버튼 뗐을 시
        else if(Input.GetMouseButtonUp(0))
        {
            //위치
            this.endPos = Input.mousePosition.x;
            Debug.LogFormat("endPos: {0}", endPos);

            float distanceX = endPos - startPos;
            Debug.LogFormat("distanceX : {0}", distanceX);

            moveSpeed = distanceX / 1000f;
            Debug.LogFormat("moveSpeed: {0}", moveSpeed);

            this.PlayMoveSound();

        }

        this.gameObject.transform.Translate(moveSpeed, 0, 0);
        moveSpeed *= dampingCoeffient;
    }

    public void PlayLoseSound()
    {
        AudioClip audio = this.audioClips[1];
        GetComponent<AudioSource>().PlayOneShot(audio);
    }

    public void PlayMoveSound()
    {
        AudioClip audio = this.audioClips[0];
        GetComponent<AudioSource>().PlayOneShot(audio);
    }
}