신입 개발자 공부 과정

1/17 Unity - swipe car 자동차 멈추기 게임 본문

C#/수업 내용

1/17 Unity - swipe car 자동차 멈추기 게임

Lewisjkim 2022. 1. 17. 17:41

-유니티 교과서에 있는 소스로 만든 자동차 멈추기 게임-

더보기

주의할 점/참고할 점

*translate는 transform의 메서드
*text만들었을때 이벤트시스템 지우면 버튼이 안눌림니 주의 할것
*화면좌표는 픽셀단위
*캔버스 좌표와 화면좌표는 별도

순서=

1.화면에 오브젝트(소스들) 나열 = 자동차, 깃발, 지면 이미지, 목표지점 안내 TEXT UI
2.오브젝트(자동차)를 움직이게 하는 + 움직일 때 소리가 나오게 하는 컨트롤러 스크립트 작성(Car Controller) 후 적용
3.자동차와 깃발 사이의 거리를 표시, 게임 종료 판정을 위해 감독 스크립트 작성(GameDirector) 및 적용

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

public class CarController : MonoBehaviour
{
    float speed = 0;
    Vector3 startPos;
    Vector3 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;
            //this.speed = 0.2f; //초기속도 설정
        }
        if(Input.GetMouseButtonUp(0))
        {
            this.endPos = Input.mousePosition;
            float swipelength = this.endPos.x - this.startPos.x;
            this.speed = swipelength / 500;

            //마우스를 땟을때 효과음 재생
            GetComponent<AudioSource>().Play();
            
        }
        this.transform.Translate(this.speed, 0, 0); //x축으로 이동한다
        this.speed *= 0.98f;//감속
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class GameDirector : MonoBehaviour
{
    GameObject car;
    GameObject flag;
    GameObject distance;
    // Start is called before the first frame update
    void Start()
    {
        this.car = GameObject.Find("car");//Hierarchy에있는 car를 찾는다
        this.flag = GameObject.Find("flag");
        this.distance = GameObject.Find("Distance");//
    }

    // Update is called once per frame
    void Update()
    {
        float length = this.flag.transform.position.x - this.car.transform.position.x;
        if(length>=0)
        {
            this.distance.GetComponent<Text>().text = "목표지점까지" + length.ToString("F2") + "m";//텍스트에 해당내용 추가
        }
        else
        {
            this.distance.GetComponent<Text>().text = "게임 오버";//플레그를 지나면 게임오버
        }
    }
}

만들어진 파일: 녹스에서 또는 안드로이드에서 플레이 가능=

swipecarapp.apk
18.00MB