RayCasting 이란?
레이저를 쏴서 오브젝트를 인식하는 시스템이다.
화면상에서 특정 오브젝트를 인식하기 위해 레이저를 쏴서 만나는 오브젝트들을 인식하여 활용하는 시스템으로 상당히 많은 물리연산을 동반하므로 유니티에서는 RaycastHit 이라는 함수를 제공하고 있다.
정적 변수
AllLayers | Layer mask constant to select all layers. |
bounceThreshold | Two colliding objects with a relative velocity below this will not bounce (default 2). Must be positive. |
defaultContactOffset | The default contact offset of the newly created colliders. |
DefaultRaycastLayers | Layer mask constant to select default raycast layers. |
gravity | The gravity applied to all rigid bodies in the scene. |
IgnoreRaycastLayer | Layer mask constant to select ignore raycast layer. |
queriesHitTriggers | Specifies whether queries (raycasts, spherecasts, overlap tests, etc.) hit Triggers by default. |
sleepThreshold | The mass-normalized energy threshold, below which objects start going to sleep. |
solverIterationCount | The default solver iteration count permitted for any rigid bodies (default 7). Must be positive. |
정적 함수
BoxCast | Casts the box along a ray and returns detailed information on what was hit. |
BoxCastAll | Like Physics.BoxCast, but returns all hits. |
BoxCastNonAlloc | Cast the box along the direction, and store hits in the provided buffer. |
CapsuleCast | Casts a capsule against all colliders in the scene and returns detailed information on what was hit. |
CapsuleCastAll | Like Physics.CapsuleCast, but this function will return all hits the capsule sweep intersects. |
CapsuleCastNonAlloc | Casts a capsule against all colliders in the scene and returns detailed information on what was hit into the buffer. |
CheckBox | Check whether the given box overlaps with other colliders or not. |
CheckCapsule | Checks if any colliders overlap a capsule-shaped volume in world space. |
CheckSphere | Returns true if there are any colliders overlapping the sphere defined by position and radius in world coordinates. |
GetIgnoreLayerCollision | Are collisions between layer1 and layer2 being ignored? |
IgnoreCollision | Makes the collision detection system ignore all collisions between collider1 and collider2. |
IgnoreLayerCollision | Makes the collision detection system ignore all collisions between any collider in layer1 and any collider in layer2.Note that IgnoreLayerCollision will reset the trigger state of affected colliders, so you might receive OnTriggerExit and OnTriggerEnter messages in response to calling this. |
Linecast | Returns true if there is any collider intersecting the line between start and end. |
OverlapBox | Find all colliders touching or inside of the given box. |
OverlapBoxNonAlloc | Find all colliders touching or inside of the given box, and store them into the buffer. |
OverlapSphere | Returns an array with all colliders touching or inside the sphere. |
OverlapSphereNonAlloc | Computes and stores colliders touching or inside the sphere into the provided buffer. |
Raycast | Casts a ray, from point origin, in direction direction, of length maxDistance, against all colliders in the scene. |
RaycastAll | Casts a ray through the scene and returns all hits. Note that order is not guaranteed. |
RaycastNonAlloc | Cast a ray through the scene and store the hits into the buffer. |
SphereCast | Casts a sphere along a ray and returns detailed information on what was hit. |
SphereCastAll | Like Physics.SphereCast, but this function will return all hits the sphere sweep intersects. |
SphereCastNonAlloc | Cast sphere along the direction and store the results into buffer. |
위 표처럼 수많은 도구들이 존재하는데 몇가지만 잘 사용해도 우리가 원하는 효과를 대부분 구현할 수 있다고 한다.
실제로 총을 발사하는 과정을 구현해보았다.
효과를 위한 Prefab들이 몇가지 필요하긴 하지만 손쉽게 구현할 수 있었다.
#관련코드
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Weapon : MonoBehaviour
{
[SerializeField] Camera FPCamera;
[SerializeField] float range = 100f;
[SerializeField] float damage = 30f;
[SerializeField] ParticleSystem muzzleFlash;
[SerializeField] GameObject hitEffect;
void Update()
{
if(Input.GetButtonDown("Fire1")){
Shoot();
}
}
private void Shoot()
{
PlayMuzzleFlash();
ProcessRaycast();
}
private void PlayMuzzleFlash()
{
muzzleFlash.Play();
}
private void ProcessRaycast()
{
RaycastHit hit;
if (Physics.Raycast(FPCamera.transform.position, FPCamera.transform.forward, out hit, range))
{
CreateHitImpact(hit);
Enemy_Health target = hit.transform.GetComponent<Enemy_Health>();
if (target == null) return;
target.TakeDamage(damage);
}
else
{
return;
}
}
private void CreateHitImpact(RaycastHit hit)
{
GameObject impact = Instantiate(hitEffect, hit.point, Quaternion.LookRotation(hit.normal));
Destroy(impact, 0.1f);
}
}
#기타
위 코드에서 RaycastHit.point과 RaycastHit.normal을 사용했는데 모두 RaycastHit 함수의 프로퍼티들이다.
(1) collider
ray가 충돌한 충돌체(Collider) 이다.
(2) point
Collider와 충돌한 지점이다.
(3) normal
충돌한 지점에서 면에 수직인 법선벡터이다.
법선벡터의 길이는 1이다.
우리가 충돌한 지점을 바라보는 방향에 수직인 방향이므로 효과를 생성할때 참고한다.
(4) distance
ray의 origin으로부터 충돌한 지점까지의 거리이다./
(5) transform
충돌체의 Transform 컴포넌트이다.
(6) rigidbody
충돌체의 RigidBody 컴포넌트이다.
사실 Raycast 를 위해 어떠한 물리연산을 사용했는지도 궁금해서 기회가 된다면 좀 더 상세히 다뤄보려고 한다.
#참조
https://docs.unity3d.com/ScriptReference/Physics.Raycast.html
Unity - Scripting API: Physics.Raycast
Description Casts a ray, from point origin, in direction direction, of length maxDistance, against all colliders in the Scene. You may optionally provide a LayerMask, to filter out any Colliders you aren't interested in generating collisions with. Specifyi
docs.unity3d.com
https://coding-of-today.tistory.com/175
[유니티] 레이캐스트 총정리 - Unity Raycast
유니티에는 레이캐스트라고 해서 마치 레이저를 쏴서 오브젝트를 인식하는 시스템이 존재한다. 이러한 레이캐스트는 사실 굉장히 많은 연산이 수반되는 물리적 방식이다. 따라서 유니티에서
coding-of-today.tistory.com
https://m.blog.naver.com/happybaby56/221370502930
[유니티] RaycastHit 구조체
RaycastHit 은 Raycast 메서드 사용시에 반환받는 충돌정보를 담고 있다. 다음은 RaycastHit 구조체의...
blog.naver.com
'Unity' 카테고리의 다른 글
Unity) Event (2) | 2023.10.20 |
---|---|
Unity) Animator (2) | 2023.10.20 |
Unity) Draw gizmo selection (4) | 2023.10.17 |
Unity) Realm Rush Defense Game (0) | 2023.10.16 |
2023.02.28 Cloud Adventure (0) | 2023.05.29 |