게임 개발/유니티

20240216 Unity - Picking

싹난 감자 2024. 2. 16. 17:47

 

PickingExample.cs

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

public class PicKingExample : MonoBehaviour
{
    [SerializeField] private GameObject[] objs = null;
    private Camera mainCam = null;

    private void Update()
    {
        ResetColor();
        GameObject go = ModernPickingProcess();
        if (go != null)  SetColorAtGO(go);
    }


    private GameObject PickingProcess() { // 너무 옛날 방식 이제 안씀
        //transform.localToWorldMatrix;
        mainCam = Camera.main;
        Vector3 mousePos = Input.mousePosition; // 마우스의 위치를 구했지만 마우스는 z값이 없음. z가 0이라서 카메라보다 뒤에 있어서 위치가 안찍힘
        mousePos.z = mainCam.nearClipPlane; // 마우스를 카메라 가까이로 보내줌
        Vector3 toWorld = mainCam.ScreenToWorldPoint(mousePos);
        Vector3 dir = (toWorld - mainCam.transform.position).normalized; 

        RaycastHit hit;
        if (Physics.Raycast(mainCam.transform.position, dir, out hit)) {
            Debug.Log(hit.transform.name);
        }

        Debug.DrawLine(mainCam.transform.position, dir, Color.red); // Ray 위치 표시해줌

        return null;
    }

    private GameObject ModernPickingProcess() { // 알아서 레이 다 만들어줌 요즘방식
        mainCam = Camera.main;
        Ray ray = mainCam.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit)) {
            return hit.transform.gameObject;
        }
        return null;
    }

    private void ResetColor() {
        foreach (GameObject go in objs) {
            MeshRenderer mr = go.GetComponent<MeshRenderer>();
            mr.material.SetColor("_Color", Color.white);
        }
    }

    private void SetColorAtGO(GameObject _go) {
        MeshRenderer mr = _go.GetComponent<MeshRenderer>();
        mr.material.SetColor("_Color", new Color(1f,0f,0f));
    }
}

 

 

 

PickingMove.cs

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

public class PickingMove : MonoBehaviour
{
    private Transform pointTr = null;
    private float moveSpeed = 10f;
    private Vector3 pointPos = Vector3.zero;
    private bool isMoving = false;
    private const float stopDistance = 0.02f;

    private void Awake()
    {
        pointTr = GameObject.FindGameObjectWithTag("PickingPoint").transform;
    } 

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
            isMoving = PickingProcess(ref pointPos);

        if (isMoving)
        {
            SetPointPosition(pointPos);
            MovingToPoint(pointPos);
            //transLookAt(pointPos);
        }
    }

    private bool PickingProcess(ref Vector3 _point) {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit)) {
            _point = hit.point;
            return true;
        }

        return false;
    }

    private void MovingToPoint(Vector3 _point)
    {
        _point.y = transform.position.y; // rigidbody 들어있어서 y값 보정해줘야함. 안그러면 마우스로 찍는게 땅이라서 땅 파고 들어가려다 막혀서 빌빌거림
        Vector3 dir = _point - transform.position;
        dir.Normalize();

        transform.rotation = Quaternion.Lerp(this.transform.rotation, Quaternion.LookRotation(dir), Time.deltaTime * moveSpeed);
        transform.position = transform.position + (dir * moveSpeed * Time.deltaTime);

        /*Vector3 dist = transform.position - _point;
        dist.magnitude // 벡터의 길이*/
        if (Vector3.Distance(transform.position, _point) < stopDistance) {
            isMoving = false;
        }
    }

    private void SetPointPosition(Vector3 _pos) {
        pointTr.position = _pos;
    }

}

'게임 개발 > 유니티' 카테고리의 다른 글

20240222 Unity - Layer  (0) 2024.02.22
20240219 Unity - Prefab  (1) 2024.02.19
20240215 Unity - Rotate  (1) 2024.02.15
20240214 Unity - Transformation  (1) 2024.02.14
20240208 Unity - MiniGame  (0) 2024.02.13