본문 바로가기
유니티 기초

unity 2d 복습

by 노재두내 2023. 8. 3.

1. SwipeCar

void Start()
    {
        BoxCollider collider = this.gameObject.GetComponent<BoxCollider>();
        Debug.LogFormat("collider:{0}",collider);

        Transform trans = this.gameObject.GetComponent<Transform>();
        Debug.LogFormat("transform:{0}",trans);
    }

내가 붙어있는 게임오브젝트에 붙어 있는 T타입의 컴포넌트 인스턴스를 가져온다

내가 붙어 있는 게임오브젝트의 Transform 컴포넌트 인스턴스

 

[SerializeField] 

private 어쩌구 : private 맴버도 인스펙터에 노출할 수 있다.

 

Debug.LogFormat("<color=red>transform:{0}</color>",trans); -> 색상 바꾸기

 

void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            this.transform.Translate(1, 0, 0);
        }
    }

마우스 왼쪽 버튼 누를때마다  x축으로 1 씩 이동

 

 

void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            this.moveSpeed = 0.2f;
        }

        this.transform.Translate(this.moveSpeed, 0, 0);
    }

마우스 왼쪽 버튼 누르면 "매 프레임"마다 x축으로 이동

 

 

자동차를 z축으로 회전한 후

this.transform.Translate(this.moveSpeed, 0, 0,Space.World); --> 바퀴를 든 채로 직선으로 움직임

this.transform.Translate(this.moveSpeed, 0, 0,Space.Self); --> 회전된 방향으로 직진 

 

 

-------------------------------------전체 코드 -------------------------------------------

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

public class CarController : MonoBehaviour
{
    private float moveSpeed = 0;
    private float dampingCoeffient = 0.96f;
    private Vector3 startPos;
    // 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;
        }
        else if (Input.GetMouseButtonUp(0))
        {
            Vector3 endPos = Input.mousePosition;
            float swipeLength = endPos.x - startPos.x;

            Debug.Log(swipeLength);// 대충 500 언저리로 나옴 

            this.moveSpeed = swipeLength / 500f;
            Debug.LogFormat("moveSpeed: {0}", this.moveSpeed);
        }
        this.transform.Translate(this.moveSpeed, 0, 0);
        this.moveSpeed *= this.dampingCoeffient;//속도 감소 이거 안하면 계속 나감 
    }
}

UI는 GameDirector로 관리한다 .

Find 메서드를 통해 이름으로 gameobject를 찾을 수 있다.  -> this.carGo = GameObject.Find("car");

--------------------------UI 추가 전체 코드---------------------------------

using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UI;
public class GameDirector : MonoBehaviour
{
    GameObject carGo;
    GameObject flagGo;
    GameObject distanceGo;
    // 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");

    }
    // Update is called once per frame
    void Update()
    {
        float distanceX = this.flagGo.transform.position.x - this.carGo.transform.position.x;// 깃발과 차사이의 거리를 distanceX에 저장
        Text text = distanceGo.GetComponent<Text>();// Distance GameObject에서 Text타입의 Text 컴포넌트? 가져와서 text에 저장
        distanceX.ToString();//깃발과 차 사이의 거리를 문자열로 변환
        text.text = string.Format("목표지점까지 거리{0:0.00}m", distanceX);

        if (distanceX <= 0)
        {
            text.text = string.Format("GAME OVER");
        }
    }
}

'유니티 기초' 카테고리의 다른 글

캐릭터 타겟을 향해 대각선으로 움직이기  (0) 2023.08.04
밤송이 던지기  (0) 2023.08.04
hero 달리고 점프  (0) 2023.08.03
hero 달리기 애니메이션  (0) 2023.08.03
고양이 구름  (0) 2023.08.02