레이캐스트(RayCast)

테라핀·2022년 5월 10일
0
  • 발단 : 2d 게임 튜토리얼 만드는데 점프하는 모션을 수정하는 부분에서 DrawRay, RaycastHit2D 등의 생소한 변수와 구조체를 알게됨
//Landing Platform
        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);
                //Debug.Log(rayHit.collider.name);
            }
        }
//출처: 골드메탈(https://youtu.be/2SikOdH7xvQ)
Ray의 쓰임새 :
점프할 때 바닥와 캐릭터가 붙어있는지, 얼마나 떨어져있는지 측정하는 용도로 쓰인다. 떨어져있으면 점프모션을 쓰고, 바닥과 붙어있다면 착지/걷기 모션으로 돌아가는 둥의 형식으로 사용하면 된다.
(+추가 예시) 몬스터가 좌우로 왔다갔다하면서 이동하는데 땅끝일 때 Ray를 이용해서 떨어지지않게 설정할 수 있다. Ray를 통해 땅끝임을 감지하면 반대방향으로 움직여서 안 떨어지는 방법이 대표적이다.

DrawRay

Debug.DrawRay(Vector3 start, Vector3 dir, Color color);
//에디터에서 보이는 선(ray)을 그리기(시작, 방향, 컬러)
Parameters
startPoint in world space where the ray should start.
dirDirection and length of the ray.
colorColor of the drawn line.
durationHow long the line will be visible for (in seconds).
depthTestShould the line be obscured by other objects closer to the camera?

RaycastHit2D

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);
    } //2D 물리학에서 레이캐스트에 의해 감지된 객체에 대해 반환된 정보
Properties
centroidThe centroid of the primitive used to perform the cast.
colliderThe collider hit by the ray.
distanceThe distance from the ray origin to the impact point.
fractionFraction of the distance along the ray that the hit occurred.
normalThe normal vector of the surface hit by the ray.
pointThe point in world space where the ray hit the collider's surface.
rigidbodyThe Rigidbody2D attached to the object that was hit.
transformThe Transform of the object that was hit.

Physics2D.Raycast 부분은 다음번 스터디때 알아보고 작성하기..
2022.5.10. 작성
2022.5.23. 수정(1차) - ray의 쓰임새 내용 추가

profile
원하는 어플이 없어서 직접 만들기로 함. 근데 다른 것도 찍먹하느라 늦음

0개의 댓글