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

public class MousePick : MonoBehaviour
{
    Vector3 dir;
    public float moveSpeed;

    private void Start()
    {
        dir = transform.position;
    }

    void Update()
    {
        // 마우스 왼쪽버튼 누르면
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hitInfo;
            int layer = 1 << LayerMask.NameToLayer("Player");
            if(Physics.Raycast(ray, out hitInfo, Mathf.Infinity, ~layer))
            {
                Debug.Log($"충돌한 오브젝트={hitInfo.collider.gameObject}, 충돌위치={hitInfo.point}");
                dir = hitInfo.point;
                dir.y = transform.position.y;
            }
        }

        transform.position = Vector3.MoveTowards(transform.position, dir, Time.deltaTime * moveSpeed);
    }
}

https://bang2019.tistory.com/37?category=789315

 

마우스 클릭

void Update() { // 마우스 왼쪽버튼 누르면 if (Input.GetMouseButtonDown(0)) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hitInfo; if(Physics.Raycast(ray, out hitInfo, Ma..

bang2019.tistory.com


 

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

public class MousePick : MonoBehaviour
{
    Vector3 dir;
    public float moveSpeed;
    public float turnSpeed;

    private void Start()
    {
        dir = transform.position;
    }

    void Update()
    {
        // 마우스 왼쪽버튼 누르면
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hitInfo;
            int layer = 1 << LayerMask.NameToLayer("Player");
            if(Physics.Raycast(ray, out hitInfo, Mathf.Infinity, ~layer))
            {
                Debug.Log($"충돌한 오브젝트={hitInfo.collider.gameObject}, 충돌위치={hitInfo.point}");
                dir = hitInfo.point;
                dir.y = transform.position.y;
            }
        }
	// 이동
        transform.position = Vector3.MoveTowards(transform.position, dir, Time.deltaTime * moveSpeed);

        // 회전
        Vector3 direction = dir - transform.position;   
        Vector3 newDir = Vector3.RotateTowards(transform.forward, direction.normalized, Time.deltaTime * turnSpeed, 0);
        transform.rotation = Quaternion.LookRotation(newDir);
    }
}

// 회전이 향하는 방향벡터. 이쪽으로 회전할 것!

Vector3 direction = dir - transform.position; 

 

// RotateTowards : m1의 벡터를 m2의 벡터로 회전시키는 것.

Vector3 newDir = Vector3.RotateTowards(transform.forward, direction.normalized, Time.deltaTime * turnSpeed, 0);

 

// rotation은 Quaternion형임. 
// LookRotation : newDir를 향하게 하는 Quaternion을 리턴.

transform.rotation = Quaternion.LookRotation(newDir);

'Unity' 카테고리의 다른 글

Resources 사용해보기  (0) 2021.05.24
캐릭터를 따라다니는 3인칭 카메라 구현  (0) 2021.05.24
마우스 클릭  (0) 2021.05.21
상속  (0) 2021.04.16
스택메모리 힙메모리  (0) 2021.04.16

+ Recent posts