pudding81 2024. 1. 28. 13:15

 

Car

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

public class CarController : MonoBehaviour
{
   
    [SerializeField] private float attenAttenuation = 0.96f;
    [SerializeField] private float divied = 500f;
    private float speed = 0;
    private Vector3 startPosition;
    

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {         
            //화면을 터치한 위치 가져오기 
            Debug.Log(Input.mousePosition);
            
            this.startPosition = Input.mousePosition;
          
        }
        else if (Input.GetMouseButtonUp(0))
        {
            //화면에서 손을 뗀 위치 가져오기
            Debug.Log(Input.mousePosition);
            
            //화면에서 손을 뗀 지점의 x - 터치한 지점의 x 길이 구하기
            float length = Input.mousePosition.x - this.startPosition.x;
          
           // 속도 구하기
            speed = length / divied; 
            Debug.LogFormat("<color=yellow>speed: {0}</color>", speed);
           
        }

        //0.1유닛씩 매 프레임마다 이동한다 
        this.gameObject.transform.Translate(new Vector3(speed, 0, 0));

        //매 프레임 마다 스피드를 감속 한다 
        speed *= attenAttenuation;
    }
}

 

 

 

UI Text

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

public class GameDirector : MonoBehaviour
{
    private GameObject carGo;
    private GameObject flagGo;
    private GameObject distanceGo; 
    private Text distanceText;  // 거리표시


    void Start()
    {
        this.carGo = GameObject.Find("car");       
       
       this.flagGo = GameObject.Find("flag");
            
       this.distanceGo = GameObject.Find("distance");
        
        distanceText =  this.distanceGo.GetComponent<Text>();
     
        
    }

    void Update()
    {
        //매프레임마다 자동차와 깃발의 거리를 계산 
        float length = this.flagGo.transform.position.x - this.carGo.transform.position.x;
       
        distanceText.text = "남은거리:"+length.ToString("0")+"m";
    }
}