새소식

⇥ 2D Game/Unity

Unity 게임 만들기 프로젝트 - 이동 구현 (Rotate)

  • -
반응형

https://jjoyling.tistory.com/177

 

Unity 게임 만들기 프로젝트 - 이동 구현 (transform)

1. 이동 구현GameObject 의 transform 을 조작하기 위해 해당 Object에 PlayerController.cs 스크립트를 연결하여 코드를 구현한다. using System.Collections;using System.Collections.Generic;using UnityEngine;public class PlayerContr

jjoyling.tistory.com

앞에서 좌표를 이동했지만 Player Game Object 는 방향을 회전하지 않고 그대로 있다. 이 부분을 해결하기 위해 Rotate 를 조절한다.

Quaternion -> 짐벌락을 방지하는 회전에 사용되는 방법으로 해당 기능을 이용하여 rotate 를 구현함

Quaternion.LookRotation() 
특정 방향을 바라보는 쿼터니언을 생성하는 함수 주어진 객체를 특정 방향을 바라보도록 회전하는데 사용된다.

Quaternion.Slerrp(quaternion a, quaternion b, float t) 
객체의 회전 시 부드러운 전환을 위해 사용되는 함수, a 에서 b 쿼터니언으로 전환되는데 t는 0~1 사이의 값으로 부드러움을 계산

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

public class PlayerController : MonoBehaviour
{
    [SerializeField]
    float _speed = 3.0f;
    void Start()
    {
        
    }

    // GameObject (Player)
        // Transform
        // PlayerController (*)
        // Transform 의 위치를 변경시켜야 하는데 자주 사용하기 때문에 transform 바로 사용

    void Update()
    {
        if (Input.GetKey(KeyCode.W))
        {
            transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(Vector3.forward), 0.2f);
            transform.position += Vector3.forward * Time.deltaTime * _speed;
        }
        if (Input.GetKey(KeyCode.S))
        {
            transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(Vector3.back), 0.2f);
            transform.position += Vector3.back * Time.deltaTime * _speed;
        }
        if (Input.GetKey(KeyCode.A))
        {
            transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(Vector3.left), 0.2f);
            transform.position += Vector3.left * Time.deltaTime * _speed;
        }
        if (Input.GetKey(KeyCode.D))
        {
            transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(Vector3.right), 0.2f);
            transform.position += Vector3.right * Time.deltaTime * _speed;
        }
        //transform   
    }
}

transform.rotation 으로 rotation 값을 Slerp 과 LookRotation 으로 방향 전환을 수행한다. 방향 벡터를 기준으로 회전
그리고 기존에 translate 를 이용하여 Player Object 가 바라보는 방향으로 전진하도록 했지만
오브젝트가 회전하면서 같이 쓰기 애매해졌기 때문에 position 을 이용하여 절대 좌표 값을 수정하도록 변경

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.