한 걸음 두 걸음

unity 정리 ] 언리얼 유니티 비교, 유니티 기초(수명주기 등), 스크립트 기초 본문

Unity

unity 정리 ] 언리얼 유니티 비교, 유니티 기초(수명주기 등), 스크립트 기초

언제나 변함없이 2019. 3. 15. 13:28
반응형

memo > 간단하게 객체 만들어보기, 0315 실습 정리완료
next 배터리없다 포스팅부터~ input event발생처리하는 것까지 다음 실습때 진행!

언리얼 유니티 비교

언리얼은 게임 제작에 최적화되어있기 때문에 개발 자유도가 낮다.(대신, 제공하고 있는 게임 설정들이 많아 빠른 시간 내에 고품질의 콘텐츠를 제작할 수 있다. 대신 unity보단 개발 난이도가 높다.) 높은 그래픽 성능을 낼 수 있으며, 개발 환경 또한 고사양이어야한다.

유니티은 개발제작이 쉽고 개발 자유도가 높아 게임 제작이 아닌 곳에서도 활용하기 쉽다. 고사양이 아닌 3D콘텐츠를 제작하기에 적합하여 모바일 콘텐츠 제작 등에 많이 쓰인다. 한 번 제작하면 PC, mobile, web 등 다양한 플랫폼으로 이식이 쉽다.

유니티 수명주기

유니티 UI에 대해 살펴봤다. 피봇은 회전 중심이다.

Reset / Awake / OnEnable은 프로그램이 실행될 때 자동으로 설정하는 부분이라 개발자의 개입이 필요없다.

Start : 프로그램이 시작되고 한 번만 호출되는 함수로, 초기화 세팅에 이용된다.
Update : 프레임(1초에 60~120번정도)마다 반복 호출되는 함수이다.
OnDestroy : 마지막 프레임 직후 실행됩니다. 소멸자 역할을 합니다.

Update 세부제어

  • fixedUpdate : 정확히 물리 계산을 한 후 실행을 시키는 등 정확한 동작을 반영할 때(주인공이 어디 부딪혀서 벽이 깨졌는데 얼마나 많이 깨질지 계산하고 반영한다.) 또는 frame interval을 제어할 때 사용합니다.
  • OnTriggerXXX : Callback 처리에 사용되는 Update 세부함수입니다.
  • OnCollisionXXX : 물리엔진처리에 사용됩니다.

유니티 디버깅

Debug.Log("출력"); 함수를 사용하여 Console창에서 디버깅을 진행할 수 있습니다.

유니티 스크립트 기초

-> 다음 실습시간에 연습할 것 같음!
Object를 이동시킬 때, transform.position 값을 많이 제어하게되는데

이를 참고하여 움직이면 된다. 3차원 정육각형의 각 꼭짓점 위치이다.

위치이동

#방법1 : transform.position += new Vector(0,0,1);
//이를 Update()에 적어주면 초당프레임수만큼 z축으로 이동한다.

#방법2 : transform.Translate(Vector3.forward);
여기서 Time.deltaTime을 많이 활용한다.(프레임과 프레임 사이의 퍼포먼스를 일정하게 유지)

회전
Transform.Rotate();를 활용한다.

참고

구체가 쌓아둔 벽면으로 날아가는 거 다시 만드려면,

구체랑 벽면Cube들에 rigidbody Component 추가해줘.

cube wall들은 Use gravity 체크 풀어주고 바닥면이나 타 큐브들과 너무 맞닿지 않게 설정해. 안그러면 튕겨나가버리니까. collision area는 딱 맞게 설정되어있으니까 신경쓰지말고.

sphere은 Use gravity하고, 중력 z방향으로 이동하게끔 하면 끝! 간단해

ACI특강때 사용했던 스크립트코드

Cam_lotate.cs

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

public class cam_lotate : MonoBehaviour
{
    public float thrust = 50.0f;
    public Rigidbody rb;

    float horizontalSpeed = 2.0f;
    float verticalSpeed = 2.0f;


    void Start()
    {
        rb = GetComponent<Rigidbody>(); //rigid body = rb 
    }

    void FixedUpdate()
    {

            float h = horizontalSpeed * Input.GetAxis("Mouse X");
            float v = /* verticalSpeed **/ Input.GetAxis("Mouse Y");


            transform.Rotate(v, h, 0);

            if (Input.GetButtonUp("Fire1"))
            {
            // Instantiate the projectile at the position and rotation of this transform
                Rigidbody insta = Instantiate(rb, transform.position, transform.rotation) as Rigidbody;
                Vector3 forw = transform.TransformDirection(Vector3.forward * 100);
                insta.AddForce(forw * thrust);
            }

    }
}

공 발사하기 .cs

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

public class camera : MonoBehaviour
{
    public Rigidbody ball;
    private float thrust = 300;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        float h = Input.GetAxis("Mouse X") ;
        float v = Input.GetAxis("Mouse Y") ;

        transform.Rotate(h, v, 0);

        if (Input.GetButton("Fire1")) //왼쪽 컨트롤 키 누르면
            ball.AddForce(transform.forward * thrust);
            //등록시켜놓은 (이동중이던)rigidbody객체가 forward방향으로 addForce됩니다.
    }
}

Instantiate 함수 사용하여 Object복제하여 발사하기.cs

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

public class camera : MonoBehaviour
{
    public Rigidbody ball;
    private float thrust = 300;

    void Update()
    {
        float h = Input.GetAxis("Mouse X") ;
        float v = Input.GetAxis("Mouse Y") ;

        transform.Rotate(h, v, 0);

        if (Input.GetButton("Fire1")) {
            Rigidbody insta = Instantiate(ball, transform.position, transform.rotation) as Rigidbody;
            Vector3 forw = transform.TransformDirection(Vector3.forward * 100);
            insta.AddForce(forw * thrust);
        }
    }
}

카메라가 공 따라가기.cs

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

public class camera : MonoBehaviour
{
    public Rigidbody rb;
    public GameObject ball;
    Vector3 dist = new Vector3(0, 0, 0);

    // Start is called before the first frame update
    void Start()
    {
        dist = ball.transform.position - transform.position; //카메라는 현재 rigidbody이기때문에 따로 명시해주지않아도 괜찮다고합니다.

    }

    // Update is called once per frame
    void Update()
    {
        transform.position = ball.transform.position - dist; //카메라의 위치는 볼의 위치 - dist 값으로 계속 설정해주어야한다.

    }
}

충돌객체 destroy.cs

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

public class BallController : MonoBehaviour
{
    private float speed;
    private Rigidbody rb;

    public Text countText;
    private int count;
    public Text winText;

    void Start()
    {
        speed = 10;
        rb = GetComponent<Rigidbody>();
        count = 0;
        SetCountText();
       winText.text = "";
    }

    void FixedUpdate()
    {
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);

        rb.AddForce(movement * speed);
    }
    /*
    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag("Box"))
        {
            other.gameObject.SetActive(false);
            count = count + 1;
            SetCountText();
        }
    }*/

    private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.CompareTag("Box"))
        {
            collision.collider.gameObject.SetActive(false); //collision.gameObject하면 공도 같이 사라져버리므로, collision.collider를 해주어야함!!
            count = count + 1;
            SetCountText();

           // Destroy(gameObject);
        }
    }

    void SetCountText()
    {
        countText.text = "Count: " + count.ToString();
        if (count >= 6)
        {
            winText.text = "You Win!";
        }
    }
}

그 외 > posting 찾아가는 것 추천

  1. Nevigation(목적지로 따라가기)
  2. button Event추가
  3. RaycastHit 등의 충돌 이벤트 처리
반응형