Unity

유니티 #3 - C# Script

kakaroo 2022. 6. 1. 09:33
반응형
유니티의 Script 에서 주로 사용되는 함수에 대한 페이지

 

1. 이동

transform.Translate(this.speed, 0, 0);

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

public class CarController : MonoBehaviour
{
    float speed = 0;
    Vector2 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;
            this.speed = 0.5f;
        }
        else if(Input.GetMouseButtonUp(0))
        {
        	Vector2 endPos = Input.mousePosition;
            float swipeLen = (endPos.x - this.startPos.x);
            
            this.speed = swipeLen / 500.0f;
            
        }
        transform.Translate(this.speed, 0, 0);        
        this.speed *= 0.95f;	//감쇠계수
    }
}

 

2. 회전

transform.Rotate(0, 0, this.speed);         

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

public class RouletteController : MonoBehaviour
{
    public float speed = 0;	//회전속도

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

    // Update is called once per frame
    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            this.speed = 10;	//10도 만큼 회전
        }
        transform.Rotate(0, 0, this.speed);
        
        this.speed *= 0.96f;	//감쇠계수
    }
}

 

감쇠계수 : 0.96f
각 프레임의 speed 값에 감쇠 계수를 곱하면 속도가 자연스럽게 줄어드는 것 처럼 보인다.
감쇠계수는 값을 변경하는 것만으로도 감속 크길ㄹ 쉽게 바꿀 수 있어 공기저항에 따른 감속이나 스프링 진동 감쇠 등 다양한 장면에서 사용된다.

 

3. UI 갱신 스크립트 (ex. Text)

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

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");
        this.flag = GameObject.find("flag");
        this.distance = GameObject.find("distance");
    }

    // Update is called once per frame
    void Update()
    {
        float len = this.flag.transform.position.x - this.car.transform.position.x;
        this.distance.GetComponent<Text>().text = "목표지점까지" + len.ToString("F2") + "미터";
    }
}
ToString("F2") => 소수점 이하 두 자리까지 표현

 

Create Empty > 위 GameDirector 스크립트로 설정

 

자신 이외의 오브젝트 컴포넌트에 접근하는 방법
1. Find 메서드로 오브젝트를 찾는다.
2. GetComponent 메서드로 오브젝트의 컴포넌트를 구한다.
3. 컴포넌트를 가진 데이터에 접근한다.

 

4. 좌우반전

GetComponent<SpriteRenderer>().flipX = true;

 

5. 키코드 입력

Input.GetKey("right")
= Input.GetKey(KeyCode.Right)

 

6. 중력 조절

낙하하지 않게 0으로 조절

Rigidbody2D rbody = GetComponent<Rigidbody2D>();
rbody.gravitiyScale = 0;

 

7. 충돌시 회전하지 않게

Inspector에서는 Constaints > Freeze Roation 에 체크

Rigidbody2D rbody = GetComponent<Rigidbody2D>();
rbody.constraints = RigidbodyConstraints2D.FreezeRotation;

 

8. 이동 2

transform.Translate 보다 자연스러운 물리엔진을 이용한 이동방법

Rigidbody2D rbody = GetComponent<Rigidbody2D>();
rbody.velocity = new Vector2(vx, vy);

 

8.1 점프

Rigidbody2D rbody = GetComponent<Rigidbody2D>();
rbody.AddForce(new Vector2(0, <점프력>), ForceMode2D.Impulse);

9. 물체를 쫒아감

Rigidbody2D rbody = GetComponent<Rigidbody2D>();
Gameobject obj = GameObject.Find("targetName");
Vector3 dir = (obj.transform.position - this.transform.position).normalized;
rbody.velocity = new Vector2(dir.x, dir.y);

 

normalized
오브젝트 균일한 이동을 위하여 벡터의 정규화가 필요.
그 이유는 모든 방향의 벡터 길이가 1 이어야 방향에 따른 이동 속도가 같아지기 때문.

 

10. 일시정지

Time.timeScale = 0;	// 1은 resume

 

11. 활성화/비활성화

Gameobject obj = GameObject.Find("targetName");
obj.SetActive(false);	//비활성화

 

12. 터치를 조사하는 법

Raycast : 터치한 점에서 안쪽방향으로 ray(광선)를 쏘아서 뭔가에 충돌하는지 여부를 조사

var wPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
var hit = Physics2D.Raycast(wPos, Vector2.zero);
if(hit) {
  if(hit.collider.gameObject.name == this.name) //충돌
    ..
}

 

13. mobile touch

1. 터치된 손가락 갯수 인식하기

// 손가락 터치가 1개 일때  
if(Input.touchCount == 1){   ...   }

// 손가락 터치가 2개 이상일때  
if(Input.touchCount >= 2){   ...   }

// 손가락 터치가 오직 1개일때만  
if(Input.touchCount < 2){   ...  }


2. 터치의 단계는 5가지

// 터치가 시작되었을 때  
if(Input.GetTouch(0).phase == TouchPhase.Began){  ... }

// 터치된 손가락이 움직일 때  
if(Input.GetTouch(0).phase == TouchPhase.Moved){ ... }

// 터치된 손가락이 그자리에 가만히 있을 때  
if(Input.GetTouch(0).phase == TouchPhase.Stationary){ ... }

// 터치된 손가락이 스크린에서 떨어질 때  
if(Input.GetTouch(0).phase == TouchPhase.Ended){ ... }

// 모바일폰을 귀에 갖다 대거나 touch tracking을 수행하지 않아야 할 경우에  
if(Input.GetTouch(0).phase == TouchPhase.Canceled){ ... }


3. 터치의 응용

// 손가락 두 개가 움직일 때  
if(Input.GetTouch(0).phase == TouchPhase.Moved && Input.GetTouch(1).phase == TouchPhase.Moved){ ... }

// 손가락 하나는 가만히 있고 다른 하나는 움직일 때  
if(Input.GetTouch(0).phase == TouchPhase.Stationary && Input.GetTouch(1).phase == TouchPhase.Moved){ ... }

// 손가락 한 개가 스크린을 움직일 때 속도  
if(Input.GetTouch(0).phase == TouchPhase.Moved) {
	float speedX = Input.GetTouch(0).deltaPosition.x / Input.GetTouch(0).deltaTime;   // 횡방향 속도      float speedY = Input.GetTouch(0).deltaPosition.y / Input.GetTouch(0).deltaTime;   // 종방향 속도
}

// 스크린 찍은 위치에서 Raycast 할 때  
if(Input.GetTouch(0).phase == TouchPhase.Began){
	Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);     
	RaycastHit hit;     

    if(Physics.Raycast(ray, out hit, 10.0f)){
    	Instantiate(something, hit.point, Quaternion.identity);
    }
}

 

14. 오브젝트의 중첩순서 우선순위

1. Sorting Layer : 아래로 갈수록 카메라와 가까워짐

2. Order in Layer : 값이 클수록 카메라와 가까워짐

3. Position Z : 값이 작을수록 카메라와 가까워짐

 

15. 터치한 좌표 구하기

//터치한 위치를 카메라 안에서의 위치로 변환
var wPos = Camera.main.ScreenToWorldPoint(Input.mousePosition + Camera.main.transform.forward);
wPos.z = -5;	//앞쪽에 표시

 

16. 게임오브젝트 범위 내의 랜덤 위치 설정

Vector3 area = GetComponent<SpriteRenderer>().bounds.size;
Vector3 newPos = this.transform.position;
newPos.x += Randon.Range(-area.x/2, area.x/2);
newPos.y += Random.Range(-area.y/2, area.y/2);

 

17. 물체를 꺼내어 던진다.

flat throwX = 4;	//던지는 힘
float throwY = 8;
Rigidbody2D rbody = GetComponent<Rigidbody2D>();
if(leftFlag) {	//왼쪽 방향이면 왼쪽으로 던진다
	rbody.AddForce(new Vector2(-throwX, throwY), ForceMode2D.Impulse);
} else {	//오른쪽 방향이면 오른쪽으로 던진다
	rbody.AddForce(new Vector2(-throwX, throwY), ForceMode2D.Impulse);
}

 

18. 카메라가 게임 오브젝트를 뒤쫓아 간다.

Vector3 basePos;	//높이는 일정하게 유지하기 위해

void Start()
{
	basePos = Camera.main.gameObject.transform.position;	
}

void LastUpdate()  //모든 게임 오브젝트의 이동이 끝난 후에 행한다
{
    Vector3 pos = this.transform.position;
    pos.z = -10;	//카메라이므로 앞으로 이동시킨다
    pos.y = basePos.y;
    Camera.main.gemaObject.transform.position = pos;
}
반응형