vanilladocs
vanillapunch.com
API / misc/collision2d

misc/collision2d

2D 충돌 유틸.

  • 원본 misc/collision2d.js 를 옮긴 것이다. 원-원 겹침 분리(밀어내기)와 반경 안 최근접 찾기처럼 액션 게임마다 다시 만들던 판정을 모았다.
  • 모두 정적 함수다.
  • 원본과 다른 점: resolve_circle_overlap 은 null 대신 None, { push_a, push_b } 대신 CircleOverlapPush 를 돌려준다. find_nearest_in_radius 는 대상의 참조를 돌려주고, 고칠 때 쓰도록 번호를 돌려주는 find_nearest_index_in_radius 를 더했다. is_static_b 기본값(false)은 러스트에 기본 인자가 없어 늘 넘긴다.

2D collision utility.

  • A port of the original misc/collision2d.js. Gathers checks that were rebuilt in every action game, like circle-circle overlap separation (pushing apart) and finding the nearest within a radius.
  • All functions are static.
  • Differences from the original: resolve_circle_overlap returns None instead of null, and CircleOverlapPush instead of { push_a, push_b }. find_nearest_in_radius returns a reference to the target, and find_nearest_index_in_radius, which returns an index for modifying, is added. The is_static_b default (false) is always passed because Rust has no default arguments.

CircleOverlapPushstruct traits Clone, Copy, Debug, PartialEq

소스source

원-원 겹침을 풀 이동량. (원본 { push_a, push_b })

  • Collision2D::resolve_circle_overlap 이 돌려준다. 두 위치에 각각 더하면 겹침이 풀린다.

Offsets that resolve a circle-circle overlap. (original { push_a, push_b })

  • Returned by Collision2D::resolve_circle_overlap. Adding each to its position resolves the overlap.
예제Example겹친 두 원을 반씩 떼어 놓기Push two overlapping circles apart by half each
use vanilla::{Collision2D, Vector2};

let mut position_a = Vector2::create(0.0, 0.0);
let mut position_b = Vector2::create(6.0, 0.0);
if let Some(circle_overlap_push) = Collision2D::resolve_circle_overlap(position_a, 4.0, position_b, 4.0, false) {
	position_a += circle_overlap_push.push_a;
	position_b += circle_overlap_push.push_b;
}
assert_eq!(position_a, Vector2::create(-1.0, 0.0));
assert_eq!(position_b, Vector2::create(7.0, 0.0));
assert!(!Collision2D::test_circle_overlap(position_a, 4.0, position_b, 4.0));
필드fieldpub push_a: Vector2#0.3.2 부터since 0.3.2소스source

A 에 더할 이동량. (B 에서 멀어지는 쪽)

Offset to add to A. (away from B)

반환ReturnsVector2

필드fieldpub push_b: Vector2#0.3.2 부터since 0.3.2소스source

B 에 더할 이동량. (A 에서 멀어지는 쪽, B 가 고정물이면 0)

Offset to add to B. (away from A, 0 if B is static)

반환ReturnsVector2

Collision2Dstruct

짝Counterpart: vanilla.js Collision2D소스source

2D 충돌 유틸. (정적 함수 묶음)

2D collision utility. (a set of static functions)

예제Example벽(고정물)에 박힌 원 밀어내기Push a circle stuck in a wall (static object) out
use vanilla::{Collision2D, Vector2};

let wall_position = Vector2::create(10.0, 0.0);
let mut hero_position = Vector2::create(4.0, 0.0);
if let Some(circle_overlap_push) = Collision2D::resolve_circle_overlap(hero_position, 3.0, wall_position, 5.0, true) {
	hero_position += circle_overlap_push.push_a;
}
assert_eq!(hero_position, Vector2::create(2.0, 0.0));
예제Example반경 안에서 가장 가까운 적 고르기Pick the nearest enemy within a radius
use vanilla::{Collision2D, Vector2};

struct Enemy {
	position: Vector2,
	health: i32,
}

let mut enemy_list = vec![
	Enemy { position: Vector2::create(30.0, 0.0), health: 3 },
	Enemy { position: Vector2::create(8.0, 6.0), health: 3 },
];
let center = Vector2::zero();
if let Some(enemy_index) = Collision2D::find_nearest_index_in_radius(&enemy_list, |enemy| enemy.position, center, 20.0) {
	enemy_list[enemy_index].health -= 1;
}
assert_eq!(enemy_list[1].health, 2);
assert_eq!(enemy_list[0].health, 3);
정적staticpub fn test_circle_overlap(position_a: Vector2, radius_a: f64, position_b: Vector2, radius_b: f64) -> bool#0.3.2 부터since 0.3.2소스source

원-원 겹침 검사. (닿기만 한 것은 겹친 것이 아니다)

Circle-circle overlap test. (merely touching is not overlapping)

position_aVector2
원 A 의 중심.Center of circle A.
radius_af64
원 A 의 반지름.Radius of circle A.
position_bVector2
원 B 의 중심.Center of circle B.
radius_bf64
원 B 의 반지름.Radius of circle B.

반환Returnsbool 두 중심 거리가 반지름 합보다 작으면 true.true if the distance between the two centers is less than the sum of the radii.

짝Counterpart: vanilla.js Collision2D.testCircleOverlap

정적staticpub fn resolve_circle_overlap(position_a: Vector2, radius_a: f64, position_b: Vector2, radius_b: f64, is_static_b: bool) -> Option<CircleOverlapPush>#0.3.2 부터since 0.3.2소스source

원-원 겹침 분리. (겹쳐 있으면 서로 절반씩 밀어낼 이동량, 안 겹치면 None)

  • is_static_b 면 B 는 고정물로 보고 A 만 겹친 깊이 전체를 밀린다.
  • 두 중심이 거의 같으면 x 축으로 밀어낸다.

Circle-circle overlap separation. (offsets that push each other out by half if overlapping, None if not)

  • If is_static_b, B is treated as static and only A is pushed by the full overlap depth.
  • If the two centers are nearly the same, pushes along the x axis.
position_aVector2
원 A 의 중심.Center of circle A.
radius_af64
원 A 의 반지름.Radius of circle A.
position_bVector2
원 B 의 중심.Center of circle B.
radius_bf64
원 B 의 반지름.Radius of circle B.
is_static_bbool
참이면 B 는 움직이지 않고 A 만 밀린다. (원본 기본값 false)If true, B does not move and only A is pushed. (original default false)

반환ReturnsOption<CircleOverlapPush> 겹쳐 있으면 A, B 에 더할 이동량. 닿기만 했거나 떨어져 있으면 None.Offsets to add to A and B if overlapping. None if merely touching or apart.

짝Counterpart: vanilla.js Collision2D.resolveCircleOverlap

정적staticpub fn find_nearest_index_in_radius<T>(target_list: &[T], get_position_handler: impl Fn(&T) -> Vector2, center: Vector2, radius: f64) -> Option<usize>#0.3.2 부터since 0.3.2소스source

반경 안 최근접 대상 번호 찾기. (중심에서 radius 안에 있는 것 가운데 가장 가까운 것, 거리가 같으면 뒤의 것)

  • 반경 경계 위의 대상도 든다.

Finds the index of the nearest target within a radius. (the nearest of those within radius of the center, the later one on a tie)

  • Targets on the radius boundary are included.
target_list&[T]
찾을 대상 목록.List of targets to search.
get_position_handlerimpl Fn(&T) -> Vector2
대상의 위치를 꺼내는 함수.Function that extracts a target's position.
centerVector2
찾을 중심.Center to search from.
radiusf64
찾을 반경.Radius to search within.

반환ReturnsOption<usize> 가장 가까운 대상의 번호. 반경 안에 하나도 없으면 None.Index of the nearest target. None if none are within the radius.

짝Counterpart: vanilla.js Collision2D.findNearestIndexInRadius

정적staticpub fn find_nearest_in_radius<T>(target_list: &[T], get_position_handler: impl Fn(&T) -> Vector2, center: Vector2, radius: f64) -> Option<&T>#0.3.2 부터since 0.3.2소스source

반경 안 최근접 대상 찾기. (투사체 명중 판정처럼)

  • 고르는 규칙은 find_nearest_index_in_radius 와 같다.

Finds the nearest target within a radius. (like a projectile hit check)

  • The picking rule is the same as find_nearest_index_in_radius.
target_list&[T]
찾을 대상 목록.List of targets to search.
get_position_handlerimpl Fn(&T) -> Vector2
대상의 위치를 꺼내는 함수.Function that extracts a target's position.
centerVector2
찾을 중심.Center to search from.
radiusf64
찾을 반경.Radius to search within.

반환ReturnsOption<&T> 가장 가까운 대상의 참조. 반경 안에 하나도 없으면 None.Reference to the nearest target. None if none are within the radius.

짝Counterpart: vanilla.js Collision2D.findNearestInRadius

예제Example투사체 반경 안의 가장 가까운 점The nearest point within a projectile's radius
use vanilla::{Collision2D, Vector2};

let target_list = [Vector2::create(10.0, 0.0), Vector2::create(3.0, 4.0), Vector2::create(0.0, 30.0)];
let nearest_target = Collision2D::find_nearest_in_radius(&target_list, |target| *target, Vector2::zero(), 12.0);
assert_eq!(nearest_target, Some(&Vector2::create(3.0, 4.0)));
assert!(Collision2D::find_nearest_in_radius(&target_list, |target| *target, Vector2::create(100.0, 100.0), 5.0).is_none());
정적staticpub fn test_point_in_circle(point: Vector2, center: Vector2, radius: f64) -> bool#0.3.2 부터since 0.3.2소스source

점-원 포함 검사. (경계 위도 안으로 친다)

Point-in-circle test. (the boundary counts as inside)

pointVector2
검사할 점.Point to test.
centerVector2
원의 중심.Center of the circle.
radiusf64
원의 반지름.Radius of the circle.

반환Returnsbool 점이 원 안이나 경계 위면 true.true if the point is inside the circle or on its boundary.

짝Counterpart: vanilla.js Collision2D.testPointInCircle