- 발단 : 2d 게임 튜토리얼 만드는데 점프하는 모션을 수정하는 부분에서 DrawRay, RaycastHit2D 등의 생소한 변수와 구조체를 알게됨
if (rigid.velocity.y < 0)
{
Debug.DrawRay(rigid.position, Vector3.down, new Color(0, 1, 0));
RaycastHit2D rayHit = Physics2D.Raycast(rigid.position, Vector3.down, 1, LayerMask.GetMask("Platform"));
if (rayHit.collider != null)
{
if (rayHit.distance < 0.5f)
anim.SetBool("isJumping", false);
}
}
Ray의 쓰임새 :
점프할 때 바닥와 캐릭터가 붙어있는지, 얼마나 떨어져있는지 측정하는 용도로 쓰인다. 떨어져있으면 점프모션을 쓰고, 바닥과 붙어있다면 착지/걷기 모션으로 돌아가는 둥의 형식으로 사용하면 된다.
(+추가 예시) 몬스터가 좌우로 왔다갔다하면서 이동하는데 땅끝일 때 Ray를 이용해서 떨어지지않게 설정할 수 있다. Ray를 통해 땅끝임을 감지하면 반대방향으로 움직여서 안 떨어지는 방법이 대표적이다.
Debug.DrawRay(Vector3 start, Vector3 dir, Color color);
Parameters | |
---|
start | Point in world space where the ray should start. |
dir | Direction and length of the ray. |
color | Color of the drawn line. |
duration | How long the line will be visible for (in seconds). |
depthTest | Should the line be obscured by other objects closer to the camera? |
public struct RaycastHit2D
{
public Vector2 centroid { get; set; }
public Vector2 point { get; set; }
public Vector2 normal { get; set; }
public float distance { get; set; }
public float fraction { get; set; }
public Collider2D collider { get; }
public Rigidbody2D rigidbody { get; }
public Transform transform { get; }
public int CompareTo(RaycastHit2D other);
public static implicit operator bool(RaycastHit2D hit);
}
Properties | |
---|
centroid | The centroid of the primitive used to perform the cast. |
collider | The collider hit by the ray. |
distance | The distance from the ray origin to the impact point. |
fraction | Fraction of the distance along the ray that the hit occurred. |
normal | The normal vector of the surface hit by the ray. |
point | The point in world space where the ray hit the collider's surface. |
rigidbody | The Rigidbody2D attached to the object that was hit. |
transform | The Transform of the object that was hit. |
Physics2D.Raycast 부분은 다음번 스터디때 알아보고 작성하기..
2022.5.10. 작성
2022.5.23. 수정(1차) - ray의 쓰임새 내용 추가