State.IO 라는 게임에서 유저의 터치 드래그에 따라 화살표가 그려지고 움직이는 기능을 구현 해보겠습니다.
using UnityEngine;
public class ArrowDrawer : MonoBehaviour
{
LineRenderer arrowLine = null;
Vector3 drawStartPos;
Vector3 drawEndPos;
private void Start()
{
arrowLine = GetComponent<LineRenderer>();
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Debug.DrawRay(Camera.main.transform.position, ray.direction * 200, Color.red, 1f);
int layerMask = (1 << LayerMask.NameToLayer("Ground")); //레이를 쏠 바닥의 레이어 마스크
if (Physics.Raycast(ray.origin, ray.direction, out RaycastHit hit, 200f, layerMask)) //바닥에 레이 쏘기.
{
drawStartPos = hit.point; //화살표의 시작점.
}
}
else if (Input.GetMouseButton(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
int layerMask = (1 << LayerMask.NameToLayer("Ground")); //레이를 쏠 바닥의 레이어 마스크
if (Physics.Raycast(ray.origin, ray.direction, out RaycastHit hit, 200f, layerMask)) //바닥에 레이 쏘기.
{
drawEndPos = hit.point; //화살표의 끝점.
DrawArrow(drawEndPos);
}
}
}
public void DrawArrow(Vector3 pointer)
{
float arrowheadSize = 1;
pointer.y = drawStartPos.y;
float percentSize = (float)(arrowheadSize / Vector3.Distance(drawStartPos, pointer));
arrowLine.positionCount = 4;
arrowLine.SetPosition(0, drawStartPos);
arrowLine.SetPosition(1, Vector3.Lerp(drawStartPos, pointer, 0.999f - percentSize));
arrowLine.SetPosition(2, Vector3.Lerp(drawStartPos, pointer, 1 - percentSize));
arrowLine.SetPosition(3, pointer);
arrowLine.widthCurve = new AnimationCurve(
new Keyframe(0, 0.4f),
new Keyframe(0.999f - percentSize, 0.4f),
new Keyframe(1 - percentSize, 1f),
new Keyframe(1 - percentSize, 1f),
new Keyframe(1, 0f));
}
}
Input.GetMouseButtonDown(0) 으로 화살표 시작 지점을 정하고
Input.GetMouseButton(0) 으로 화살표의 끝지점을 실시간으로 업데이트 해준다.
DrawArrow(Vector3 pointer) 를 이용하여 라인렌더러의 모양을 화살표 모양으로 그려준다.
'Unity' 카테고리의 다른 글
[Unity] 자주쓰는 유니티 오픈소스 에셋(Git) (0) | 2023.02.02 |
---|---|
[Unity] 반지름 R인 원 위에 일정 간격(각도)의 위치 얻기. (0) | 2023.02.02 |
[Unity]3D 오브젝트를 UI 위치로 이동시키기. (0) | 2023.02.01 |
[Unity] 숫자 단위(K,M,B) 로 바꾸기 (0) | 2023.01.30 |