Unity
마우스 입력한 곳으로 움직이기
방프
2021. 5. 21. 16:50
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);