
마우스 커서를 눌렀다가 한쪽으로 이동한 뒤 커서를 떼면
이동한 방향으로 커서가 이동한 거리에 비례해서 자동차(car)가 이동한다.
남은 거리가 중단의 텍스트에 표시되며,
남은 거리가 0.00m가 되면
"도착!"
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 = distanceGo.GetComponent<Text>();
Debug.LogFormat("this.carGo: {0}", this.carGo); //car 게임오브젝트 인스턴스
Debug.LogFormat("this.flagGo: {0}", this.flagGo); //flag 게임오브젝트 인스턴스
Debug.LogFormat("this.distanceGo: {0}", this.distanceGo); //distance 게임오브젝트 인스턴스 (Canvas-Text)
Debug.LogFormat("distanceText: {0}", distanceText); //distance 게임오브젝트 인스턴스의 텍스트 컴포넌트
}
void Update()
{
//매 프래임마다 자동차와 깃발의 거리를 계산
float length = this.flagGo.transform.position.x - this.carGo.transform.position.x;
if (length >= 0)
{
distanceText.text = string.Format("남은 거리 {0:0.00}m", length);
}
else
{
distanceText.text = "도착!";
}
}
}
2. GameDirector.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CarController : MonoBehaviour
{
[SerializeField] private float maxSpeed = 0.1f;
[SerializeField] private float attenuation = 0.96f;
[SerializeField] private float divNum = 500f;
private float speed = 0;
private Vector3 startPosition;
void Update()
{
// 왼쪽 버튼을 눌렀다면
if (Input.GetMouseButtonDown(0))
{
Debug.Log("화면 터치 함");
//화면을 터치한 위치 가져오기
Debug.Log(Input.mousePosition);
//speed = maxSpeed;
startPosition = Input.mousePosition;
}
else if(Input.GetMouseButtonUp(0))
{
Debug.Log("화면에서 손을 뗌");
Debug.Log(Input.mousePosition);
//화면에서 손을 뗸 지점의 x - 터치한 지점의 x
float length = Input.mousePosition.x - this.startPosition.x;
Debug.Log(length);
Debug.Log(length / divNum);
speed = length/ divNum;
Debug.LogFormat($"<color=yellow>speed: {speed}</color>");
}
//0.1 유닛씩 이동한다.
this.gameObject.transform.Translate(new Vector3(speed, 0, 0));
//매 프래임마다 스피드를 감속한다.
speed *= attenuation;
}
}
3. CarController.cs
반응형
'산대특 > 게임 클라이언트 프로그래밍' 카테고리의 다른 글
[CatEscape] CatEscape 만들기 (0) | 2024.01.29 |
---|---|
[Shuriken Swipe] 수리검 이동 및 회전 + 도착 지점 계산하기 (0) | 2024.01.27 |
[Chapter3] 룰렛 회전시키기 (0) | 2024.01.26 |
GetMouseButton과 GetMouseButtonDown의 차이점 (0) | 2024.01.26 |
방향 벡터 눈으로 확인하기 (0) | 2024.01.25 |