IT/UNITY(C#)
(C#) UNITY_오브젝트 움직임 제한하기
KS짱짱맨
2020. 2. 11. 20:20
오늘 배운것
1. OnDrawGizmos() 에서 선 긋기
- Gizmos는 공간에 대한 도형? 이런걸 표현하는 방법인것 같다 (사실 정확히는 모름)
- 선을 긋기 위해서는 두개의 점(A, B) 좌표가 필요하다.
- 그리고 Gizmos.Drawline( A점, B점); 하면 가상의 선이 만들어 진다 (근데 이거는 보여주기 위한거다)
2. 범위 설정
- 점을 우선 2개(or 4개) 찍는다. 대각선 방향으로
- 각점의 x 좌표축과, y좌표축을 기준으로 삼으면 된다.
3. 범위를 넘어 갔을때 어떻게 행동할지 결정
- if(앞으로 가려고 하는 위치.x/y > 기준점.x/y)
- 로 넘어갈것 같다하면 반대방향으로 내가 가려고 하는 위치 좌표를 변경할 수 있도록 한다.
ex) 방향전환 or 특정float 더하기 빼기
쓰임새
- 어떤 이동하는 물체가 일정 범위이상 넘어가지 않도록 하고 싶을때!!!
코드
//이건 GameManager Script
public class GameManager : MonoBehaviour
public Vector2 limitePoint1;
public Vector2 limitePoint2;
private void OnDrawGizmos()
{
Vector2 lm3 = new Vector2(limitePoint2.x, limitePoint1.y);
Vector2 lm4 = new Vector2(limitePoint1.x, limitePoint2.y);
Vector2 lm1 = limitePoint1;
Vector2 lm2 = limitePoint2;
Gizmos.color = Color.red;
Gizmos.DrawLine(lm1, lm4);
Gizmos.DrawLine(lm1, lm3);
Gizmos.DrawLine(lm2, lm3);
Gizmos.DrawLine(lm2, lm4);
}
// 여기서 부터는 EmploteeControl Script
public class EmployeeControl : MonoBehaviour
Vector2 CheckTarget (Vector2 currentTarget)
{
Vector2 temp = currentTarget;
if (currentTarget.x > GameManager.gm.limitePoint2.x) // 오른쪽으로 넘어갈때
{ temp.x -= 4; }
else if (currentTarget.x < GameManager.gm.limitePoint1.x) // 왼쪽으로 넘어갈때
{ temp.x += 4; }
if(currentTarget.y > GameManager.gm.limitePoint1.y) // 위로 넘어갈때
{ temp.y -= 4; }
else if(currentTarget.y < GameManager.gm.limitePoint2.y) // 아래로 넘어갈때
{ temp.y += 4; }
return temp;
}
IEnumerator Move()
{
while(true)
{
float x = transform.position.x + Random.Range(-2f, 2f);
float y = transform.position.y + Random.Range(-2f, 2f);
Vector2 target = new Vector2(x, y);
target = CheckTarget(target);
prePosition = transform.position;
while (Vector2.Distance(transform.position, target) > 0f)
{
transform.position = Vector2.MoveTowards(transform.position, target, speed);
yield return null;
}
yield return new WaitForSecondsRealtime(0.1f);
}
}
728x90