반응형

스크립트를 작성하여 자동차를 움직여 보겠습니다 

 

Scripts 폴더에 CarCtrl 스크립트를 만들고  car1 오브젝트에 붙입니다  

그리고 잠시 Rigdbody 에서 is Kinematic을 체크합니다 

 

 

 

 

 

 

 

CarCtrl 스크립트 작성

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

public class CarCtrl : MonoBehaviour
{
    public float moveSpeed;
    bool sideMoving = true;
    bool firstInput = true;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (GameManager.instance.gameStarted)
        {
            Move();
            CheckInput();
        }

    }

    void Move()
    {
        //물체의 z축 방향(forward)으로 moveSpeed 만큼 시간 프레임에 곱해준다 
        transform.position += transform.forward * moveSpeed * Time.deltaTime;
    }


    void CheckInput()
    {
        //첫 클릭은 무시하고 리턴한다 
        if (firstInput)
        {
            firstInput = false;
            return;
        }


        //마우스를 왼쪽버튼 클릭하면
        if (Input.GetMouseButtonDown(0))
        {
            ChangeDirection();
        }
    }
    void ChangeDirection()
    {
        //sideMoving 참일때  
        if (sideMoving)
        {
            sideMoving = false;

            //y축 방향으로 90도 회전한다
            transform.rotation = Quaternion.Euler(0, 90, 0);
        }
        else
        {
            sideMoving = true;
            transform.rotation = Quaternion.Euler(0, 0, 0);
        }
    }
}

 

 

 

 

 

 

 

 

 

Move Speed 8을 넣습니다 

그리고 GameManager 스크립트를 만듭니다 

 

Hierachy 뷰에서 GameManager 오브젝트를 만들고 GameManager 스크립트를 붙입니다 

 

 

 

 

 

 

 

 

GameManager 스크립트 작성

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

public class GameManager : MonoBehaviour
{
    public static GameManager instance;

    public bool gameStarted;

    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
        }
    }

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (!gameStarted)
        {
            //마우스 클릭하면 차가 움직인다 
            if (Input.GetMouseButtonDown(0))
            {
                GameStart();
            }
        }
    }

    public void GameStart()
    {
        gameStarted = true;
    }


    public void GameOver()
    {
       
    }
}

 

 

 

 

 

 

 

 

 

 

게임을 실행시키고 자동차가  마우스를 클릭하였을때 움직이고 방향이 바뀌는지 확인합니다 

 

 

3D Game 자동차 게임 지그재그 게임 만들기 3

 

 

반응형

+ Recent posts