티스토리 뷰

C#/연습장

1.30

Game Client Lee Hwanguk 2023. 1. 30. 15:09

#~1.30 unity 복습

#프로잭트 생성 순서
프로젝트를 열고 
1. 레이아웃 설정 
2. 플랫폼 변경 
3. 해상도 설정 
씬만들어 저장 
리소스 프로젝트 넣기 
리소스 배치 
스크립트 작성 

#vector
벡터 
- 위치 벡터
A + B  = C (좌표)

- 방향 벡터 
B - A = C (A 에서 B 까지의 방향 벡터)
magnitude Returns the length of this vector (Read Only).
https://docs.unity3d.com/ScriptReference/Vector3.html

*두 점사이의 거리
float dist=Vector3.Distance(other.position, transform.position)

->Returns the distance between a and b. (a와b사이의 거리를 반환한다)

https://docs.unity3d.com/kr/530/ScriptReference/Vector3.Distance.html

 

Vector3-Distance - Unity 스크립팅 API

Returns the distance between a and b.

docs.unity3d.com


*화면 클릭 감지
Input.GetMouseButtonDown(0); //마우스 좌클릭
Input.GetMouseButton(0); //좌클릭 누르는중
Input.GetMouseButtonUp(0); //좌클릭 해제 시

*회전
transform.Rotate
ex)transform.Rotate(x,y,z)

*감쇄계수
ex)this.speed *= 0.98f;

*Transform.Translate 
space.Self !! Local좌표

https://docs.unity3d.com/kr/530/ScriptReference/Transform.Translate.html
->오브잭트의 위치를 기반으로 움직인다. (회전하는 수리검)

->Translate (float x, float y, float z, Space relativeTo= Space.Self);

 

Transform-Translate - Unity 스크립팅 API

Moves the transform in the direction and distance of translation.

docs.unity3d.com

*화면 스와이프
ex)this.starPos=Input.mousePosition;

https://docs.unity3d.com/ScriptReference/Input-mousePosition.html

 

Unity - Scripting API: Input.mousePosition

Input.mousePosition is a Vector3 for compatibility with functions that have Vector3 arguments. The z component of the Vector3 is always 0. The bottom-left of the screen or window is at (0, 0). The top-right of the screen or window is at (Screen.width, Scre

docs.unity3d.com

ex)The current mouse position in pixel coordinates. (Read Only). 

->pixel좌표의 현재 마우스 위치

->좌표에 주의해야한다!

#len=endPos-startPos , len을 speed에 할당



*UI
반드시 Canvas밑에 자식으로 존재해야함
UI오브젝트 생성시 Canvas,EventSystem이 생성
EventSystem 이 하는 역할은 사용자와 UI의 상호작용
UI사용 시 네임스페이스 추가(using UnityEngine.UI;)

 

 

#화면 클릭 감지(마우스 좌클릭)
Input.GetMouseButtonDown(0); //좌클릭
Input.GetMouseButton(0); //클릭을 하고있는
Input.GetMouseButtonUp(0); //클릭을 뗄때

#감쇠계수를 사용하여 회전 멈추기
*0.96

#회전 
transform.Rotate 
- overloading 
transform.Rotate(x, y, z)
https://docs.unity3d.com/ScriptReference/Transform.Rotate.html

#UI
ui는 반드시 canvas밑에 자식으로 존재해야함
UI오브젝트를 생성하게되면 canvas,eventsystem이 함께 생성
UI좌표는 또 다른 좌표체계

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

public class CarController : MonoBehaviour
{
    private float speed = 0f;
    private Vector3 startPos;

    //이벤트 함수
    //인스턴스화 될때 한번 호출된다
    private void Awake() //Awake-Start
    {
        
    }
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        //화면을 클릭하면?
        if (Input.GetMouseButtonDown(0))
        {
            //Debug.Log("이동");
            //this.speed = 0.2f;
            //Debug.Log(Input.mousePosition); //픽셀의 좌표, 3D의 좌표 아님
            //Debug.LogFormat("start:{0}", Input.mousePosition);
            this.startPos = Input.mousePosition;
        }
        else if(Input.GetMouseButtonUp(0))
        {
            Debug.LogFormat("start:{0}",this.startPos);
            Debug.LogFormat("end:{0}",Input.mousePosition);
            var endPos=Input.mousePosition;
            //var c=endPos- this.startPos;
            float len=endPos.x-this.startPos.x; //x좌표상의 두 점의 거리
            Debug.LogFormat("len:{0}",len);

            this.speed = len / 500f;

            //사운드 재생
            this.GetComponent<AudioSource>().Play();
        }

        //현제 나의 위치에서 this.speed만큼 더해 위치 변경
        this.transform.Translate(this.speed, 0, 0); //x축으로 0.2유닛씩 매 프레임마다 위치 변경(x축으로 이동)

        this.speed *= 0.96f; //감쇄계수로 서서히 속도를 늦추자

    }
}
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"); //없다면 null반환
        this.flag = GameObject.Find("flag");
        this.distance = GameObject.Find("Distance");

        Debug.LogFormat("car:{0}",this.car);
        Debug.LogFormat("flag:{0}", this.flag);
        Debug.LogFormat("distance:{0}", this.distance);
    }

    // Update is called once per frame
    void Update()
    {
        //두 점(위치벡터) 사이의 거리르 계산
        //A:car
        //B:flag
        //B-A=C
        //거리는? C.magnitude

        //Vector2.Distance(A, B);

        //var a=this.car.transform.position;
        //var b=this.flag.transform.position; //월드 좌표
        //var c = b - a;
        //var len=Vector2.Distance(a,b);
        //Text uiDistrance=this.distance.GetComponent<Text>();
        //uiDistrance.text = string.Format("목표 지점 까지 {0:F2}m", len);

        var ax = this.car.transform.position.x;
        var bx = this.flag.transform.position.x;
        var cx = bx - ax;
        Debug.LogFormat("cx: {0}", cx);
        Text textDistance = this.distance.GetComponent<Text>();
        if (cx >= 0)     //자동차가 깃발보다 왼쪽에 있다면 
        {
            textDistance.text = string.Format("목표 지점 까지 {0:F2}m", cx);
        }
        else
        {
            textDistance.text = string.Format("게임 오버");
        }
    }
}

#GetObject.Find() ->씬 안에있는 이름 검색(활성화 된!)
#transforme.Traslate(x,y,z)->self(local)이 생략 , 회전하는경우를 주의.(표창 날리기 복습)

#AudioSouce쓰기 ->mp3 x ogg로 변환(용량 문제)

#Input.GetKeyDown

#Awake(인스턴스화 된 후 한번) / Start(Update 전 한번)

#좌표계:3D, Screen, UI (모두 다른 좌표계값을 가지고있음)

#거리 구하기-> b-a=c (b,a 위치벡터, Vector3 Distance(a,b) /c.megnitude로 연산가능)

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함