[ ps ]
[ 백준 / C++ ] 17471 : 게리맨더링 (tistory.com)
[ Unity ]
마우스 오른쪽 버튼을 누르면 체인이 나가고 버튼을 때면 체인을 따라 이동하는 기능을 만들고 있다.
마우스 오른쪽 버튼을 누르면 Chain State에 진입하며, 누르고 있는 중에 이동 경로를 표시하는 레이저를 생성한다.
이 레이저는 최대 사거리가 정해져 있고, 맵에 닿으면 그 부분까지 날아가게 된다.
어디까지 이동할 것인지는 Ray를 쏴서 알아봤고, 이동 경로는 LineRenderer를 통해 표현했다.
public override void Enter()
{
base.Enter();
stateMachine.player.lineRenderer.enabled = true;
}
public override void Exit()
{
base.Exit();
stateMachine.player.lineRenderer.enabled = false;
}
public override void Update()
{
base.Update();
mousePosition = Mouse.current.position.ReadValue();
ShootLaser();
}
LineRenderer가 정상적으로 그려지지 않는 버그가 존재했다.
LineRenderer를 Player 게임 오브젝트 안에 넣어놓아서 포지션을 월드가 아닌 로컬해야 했고,
RayCastHit에 저장된 값에 시작(Player) 위치를 빼줌으로써 이를 고려하였다.
void ShootLaser()
{
Vector2 mouseWorldPosition = Camera.main.ScreenToWorldPoint(mousePosition);
Vector2 playerPosition = stateMachine.player.transform.position;
Vector2 direction = (mouseWorldPosition - playerPosition).normalized;
RaycastHit2D hit = Physics2D.Raycast(playerPosition, direction, maxChainDistance, targetLayer);
Vector2 endPosition;
if (hit.collider != null)
{
endPosition = hit.point - playerPosition;
}
else
{
endPosition = direction * maxChainDistance;
}
DrawLaser(new Vector2(0f, 0f), endPosition);
}
반면 Debug.DrawLine 메서드를 통해 그린 선과 LineRenderer를 비교했을 때 길이가 맞지 않는 오류가 여전히 존재했다.
Scene 창을 비교해보니 길이가 2배 정도 차이가 났고, 알고보니 Player의 Scale을 건들인 것이 원인이었다.
Player의 lossyScale을 LineRenderer 포지션을 잡을 때 고려해줌으로써 오류를 해결했다.
void DrawLaser(Vector2 start, Vector2 end)
{
Vector2 scaledEnd = new Vector2(end.x / stateMachine.player.transform.lossyScale.x, end.y / stateMachine.player.transform.lossyScale.y);
stateMachine.player.lineRenderer.SetPosition(0, start);
stateMachine.player.lineRenderer.SetPosition(1, scaledEnd);
}
'TIL' 카테고리의 다른 글
[ 24.08.05 ] 내일배움캠프 TIL - 코루틴, 회전 (0) | 2024.08.05 |
---|---|
[ 24.07.25 ] 내일배움캠프 TIL - Animation Trigger, 경사로 판정 (0) | 2024.07.25 |
[ 24.07.10 ] 내일배움캠프 TIL - Attack Trigger2 (0) | 2024.07.10 |
[ 24.07.09 ] 내일배움캠프 TIL - Rigidbody에 Force적용 (0) | 2024.07.09 |
[ 24.07.05 ] 내일배움캠프 TIL - 2D게임에서 Ground 판단하기 (0) | 2024.07.06 |