ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Unity 2D] Fly Bird 회전 구현하기
    Unity 2D 2023. 3. 21. 20:55

    위 아래 움직이게 구현한 Bird를 이번엔 회전시켜보자.

    스페이스바 혹은 마우스 좌클릭을 했을 때 (위로 올라갈 때) 30도 회전할 수 있게 하고,

    위로 올라갔다가 아래로 떨어질 때 -90도 (수직낙하)할 수 있게 로테이션에 변화를 줄 것이다. 휴..

     

    Velocity 기본 y값이 0일 때의 Bird의 rotation은 정면을 향한다.

    Velocity y값이 0이상일 때의 Bird의 rotation은 +30도로 나타낼 것이다.

    Velocity y값이 0 아래일 때의 Bird의 rotation은 -90도로 나타낼 것이다.

     

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class Player : MonoBehaviour
    {
    	// Jump 구현
        Rigidbody2D rb;
        [SerializeField] float Speed = 5;
        private bool keyJump = false;
        
        // Rotate 구현
        private Vector3 birdRotation;
        [SerializeField] private float upRotate = 5f;
        [SerializeField] private float downRotate = -5f;
    }

    Rotate를 구현하기 위해 선언을 했다.

     

    birdRotation 변수는 Transform rotation을 저장하는데,

    이 때 Transform.rotationQuaternion을 기반으로 값을 받는다.

    rotation 값을 받아서 초기화하기 위해서는 쿼터니언 값을 오일러각으로 변환시켜 받아야 한다.

    (그냥 Vector3 객체를 넘겨주게 되면 오류가 발생한다.)

     

    upRotate 는 Bird가 위로 올라가면서 Rotate할 때 누적하여 받을 각도의 변수이다.

    downRotate도 마찬가지로 Bird가 아래로 내려가면서 Rotate할 때 누적하여 받을 각도의 변수이다.

     

     

    void RotateBird()
    {
    	// Rotate값을 저장할 변수를 초기화했다
    	float degree = 0;
        
        // 점프해서 올라갔을 때 +30도까지 회전한다
        if(rb.velocity.y > 0)
        {
        	degree = upRotate;
        }
        
        // 점프 후 내려갈 때 -90도까지 회전한다
        else if(rb.velocity.y < 0)
        {
        	degree = downRotate;
        }
        
        // birdRotation은 transform 이기 때문에 오일러 값으로 변환해 적용시켜준다
        // 회전을 구현할 때 z값만 변하기 때문에 x와 y값은 0으로 둔다
        birdRotation = new Vector3(0,0,Mathf.Clamp((birdRotation.z + degree), -90, 30));
        transform.eulerAngles = birdRotation;
    }

    degree는 upRotate 혹은 downRotate 를 누적해서 저장해주는 변수이다.

    degree는 velocity.y 가 0보다 높아지면 upRotate (+5) 를 저장하고

    velocity.y가 0보다 낮아지면 downRotate (-5) 를 저장한다.

     

    Mathf.Clamp 는 주어진 최솟값과 최댓값 사이에 주어진 값을 고정시켜준다.

    즉, 지정된 float 값이 최솟값보다 작을 경우엔 정해진 최솟값을 반환시키고

    지정된 float 값이 최댓값보다 클 경우엔 정해진 최댓값을 반환시킨다.

    transform.position = new Vector3(0,0,Mathf.Clamp(transform.position.z),MinZ,MaxZ);

    조금 더 쉽게 생각해서

    transform.position.z 는 MinZ 보다 작아질 경우 MinZ를 반환하고 MaxZ 보다 클 경우 MaxZ를 반환한다.

     

     birdRotation = new Vector3(0, 0, Mathf.Clamp((birdRotation.z + degree), -90, 30));

    위 코드도 birdRotation이 (0,0,z) 값을 받는다고 가정하면 이 z의 값은

    degree 를 (+5 혹은 -5씩) 누적하여 최솟값 혹은 최댓값에 도달할 수 있다.

    Mathf.Clamp 를 사용함으로써 -90 아래로 내려가면 -90 을, 30 위로 올라가면 30을 받는다는 것이다.

     

    그리고 birdRotation 은 위에서 말했듯이 쿼터니언 값을 기반으로 받기 때문에

    오일러 각으로 변환시켜준다.

    transform.eulerAngles = birdRotation;

     

    올라갈 때 Bird 의 얼굴이 위로 회전된 것을 알 수 있다...

    내려갈 때도 역시 바닥을 향해 회전하고 있다...

     

     

     

     

    이렇게 Bird 의 회전을 구현했다...!

     


    전체 코드

    더보기
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class Player : MonoBehaviour
    {
    	Rigidbody2D rb;
        
    	// Jump 구현
        [SerializeField] float Speed = 5;
        private bool keyJump = false;
        
        // Rotate 구현
        private Vector3 birdRotation;
        [SerializeField] private float upRotate = 5f;
        [SerializeField] private float downRotate = -5f;
        
        void Start()
        {
        	// RigidBody2D 컴포넌트를 rb라는 변수를 통해 가져온다
            rb = GetComponent<Rigidbody2D>();
        }
    
        void Update()
        {
        	// Jump를 입력받는 메서드를 따로 생성했다.
        	InputBird();
            RotateBird();
        }
        
        private void FixedUpdate()
        {
        	// 입력받은 Jump값이 true라면
        	if(keyJump == true)
            {	
            	// JumpBird메서드 받기
            	JumpBird();
                // 그리고 다시 keyJump값은 false로 만들어준다.
                keyJump = false;
            }
        }
    
        void JumpBird()
        {
        	// RigidBody2D의 Velocity는 Speed만큼 올라간다
            rb.velocity = Vector3.up * Speed;
        }
        
        void RotateBird()
    	{
    		// Rotate값을 저장할 변수를 초기화했다
    		float degree = 0;
        
        	// 점프해서 올라갔을 때 +30도까지 회전한다
        	if(rb.velocity.y > 0)
        	{
        		degree = upRotate;
        	}
        
        	// 점프 후 내려갈 때 -90도까지 회전한다
        	else if(rb.velocity.y < 0)
        	{
        		degree = downRotate;
        	}
        
        	// birdRotation은 transform 이기 때문에 오일러 값으로 변환해 적용시켜준다
            // 회전을 구현할 때 z값만 변하기 때문에 x와 y값은 0으로 둔다
        	birdRotation = new Vector3(0,0,Mathf.Clamp((birdRotation.z + degree), -90, 30));
        	transform.eulerAngles = birdRotation;
    	}
        
        void InputBird()
        {
        	// 스페이스바 혹은 마우스 좌버튼을 눌렀을 때
            keyJump |= Input.GetKeyDown(KeyCode.Space);
            keyJump |= Input.GetMouseButtonDown(0);
        }
    }
Designed by Tistory.