유니티 심화

절대강좌 유니티 - Quaternion.LookRotation

다모아 2023. 8. 21. 11:38

 

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

public class QuaternionPlayerController : MonoBehaviour
{
    [SerializeField]
    private float moveSpeed = 1f;
    private Quaternion rot;
    // Start is called before the first frame update
    void Start()
    {
        Ray ray = new Ray(this.transform.position, this.transform.forward);
        RaycastHit hit;
        DrawArrow.ForDebug(ray.origin, ray.direction * 100f, 5f, Color.green, ArrowType.Solid);
        if(Physics.Raycast(ray, out hit, 100f))
        {
            this.rot = Quaternion.LookRotation(hit.normal);
        }
    }

    // Update is called once per frame
    void Update()
    {
        this.transform.Translate(Vector3.forward * this.moveSpeed * Time.deltaTime);
    }

    private void OnTriggerEnter(Collider other)
    {
        if(other.tag == "Wall")
        {
            this.moveSpeed = 0f;
            this.transform.rotation = this.rot;

        }
    }
}

 

Ray ray는 마우스만 아니라 transform으로도 사용이 가능하다.

 

벽 위치를 돌려도 방향벡터에 따라 캐릭터가 등지는 모습