Skip to content

Commit afd7cee

Browse files
Paul V Cravenclaude
andcommitted
Add get_collision_info for push-out direction and depth
get_collision_info(sprite1, sprite2) returns a CollisionInfo with the smallest move that separates two colliding sprites: a unit normal (the direction to move sprite1) and a depth in pixels. It returns None exactly when check_for_collision returns False. It uses the same distance, bounding box, and separating axis stages as check_for_collision, keeping the overlap on each axis instead of only checking for separation. The bounding boxes give the x and y overlaps; the cached edge normals give the rest, divided by their length to get pixels. Ties prefer the y axis, then x, then other edges, and up or right over down or left. Correct for convex hit boxes. check_for_collision is unchanged. get_collision_info costs about 1.2-1.4x as much for overlapping sprites and the same otherwise. Add it to benchmarks/collisions/micro.py. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent d771686 commit afd7cee

6 files changed

Lines changed: 297 additions & 2 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ Arcade [PyPi Release History](https://pypi.org/project/arcade/#history) page.
3434
- Added `arcade.CollisionMethod`, an enum for the `method` argument of `check_for_collision_with_list` and `check_for_collision_with_lists`: `AUTO`, `SPATIAL`, `GPU`, and `SIMPLE`. It's an `IntEnum`, so the numbers `0` to `3` still work.
3535
- Added `arcade.has_collision_with_list()` and `arcade.has_collision_with_lists()`, which return `True` as soon as they find a collision. They're faster than checking whether `check_for_collision_with_list()` returns an empty list, by about 18x when many sprites overlap.
3636
- Added `arcade.check_for_collision_between_lists(list_a, list_b)`, which returns every colliding `(sprite_a, sprite_b)` pair between two lists, such as bullets and enemies. Passing the same list twice returns each pair once.
37+
- Added `arcade.get_collision_info(sprite1, sprite2)`, which returns a `CollisionInfo` with the smallest move that separates two colliding sprites: a unit `normal` (the direction to move `sprite1`) and a `depth` in pixels, or `None` if they don't collide. For example, `player.position += info.normal * info.depth` pushes a player out of a wall. Correct for convex hit boxes.
3738

3839
### Misc Changes
3940
- Sped up several `SpriteList` operations: `swap()` no longer searches the draw order (about 1000x faster at the end of a 10,000 sprite list), `insert()` and item assignment check membership with a dictionary instead of scanning the list, and drawing uploads only the buffer slots in use instead of the whole capacity (moving one sprite and drawing is 1.6-2.3x faster).

‎arcade/__init__.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,8 +183,10 @@ def configure_logging(level: int | None = None):
183183

184184
from .sprite_list import SpriteList
185185
from .sprite_list import SpriteSequence
186+
from .sprite_list import CollisionInfo
186187
from .sprite_list import CollisionMethod
187188
from .sprite_list import check_for_collision
189+
from .sprite_list import get_collision_info
188190
from .sprite_list import check_for_collision_with_list
189191
from .sprite_list import check_for_collision_with_lists
190192
from .sprite_list import check_for_collision_between_lists
@@ -314,6 +316,7 @@ def configure_logging(level: int | None = None):
314316
"SpriteCircle",
315317
"SpriteList",
316318
"SpriteSequence",
319+
"CollisionInfo",
317320
"CollisionMethod",
318321
"SpriteSolidColor",
319322
"Text",
@@ -331,6 +334,7 @@ def configure_logging(level: int | None = None):
331334
"Window",
332335
"astar_calculate_path",
333336
"check_for_collision",
337+
"get_collision_info",
334338
"check_for_collision_with_list",
335339
"check_for_collision_with_lists",
336340
"check_for_collision_between_lists",

‎arcade/sprite_list/__init__.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
from .sprite_list import SpriteList, SpriteSequence
22
from .spatial_hash import SpatialHash
33
from .collision import (
4+
CollisionInfo,
45
CollisionMethod,
56
get_distance_between_sprites,
67
get_closest_sprite,
78
check_for_collision,
9+
get_collision_info,
810
check_for_collision_with_list,
911
check_for_collision_with_lists,
1012
check_for_collision_between_lists,
@@ -20,10 +22,12 @@
2022
"SpriteList",
2123
"SpriteSequence",
2224
"SpatialHash",
25+
"CollisionInfo",
2326
"CollisionMethod",
2427
"get_distance_between_sprites",
2528
"get_closest_sprite",
2629
"check_for_collision",
30+
"get_collision_info",
2731
"check_for_collision_with_list",
2832
"check_for_collision_with_lists",
2933
"check_for_collision_between_lists",

‎arcade/sprite_list/collision.py‎

Lines changed: 143 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
from collections.abc import Iterable
22
from enum import IntEnum
3-
from typing import TypeVar
3+
from math import hypot
4+
from typing import NamedTuple, TypeVar
5+
6+
from pyglet.math import Vec2
47

58
from arcade.geometry import (
69
_are_polygons_overlapping_on_axes,
@@ -59,6 +62,31 @@ class CollisionMethod(IntEnum):
5962
"""
6063

6164

65+
class CollisionInfo(NamedTuple):
66+
"""
67+
How two colliding sprites overlap. Returned by :py:func:`get_collision_info`.
68+
69+
Moving the first sprite by ``normal * depth`` is the smallest move that
70+
separates the two sprites, leaving their hit boxes just touching::
71+
72+
info = arcade.get_collision_info(player, wall)
73+
if info:
74+
player.position += info.normal * info.depth
75+
"""
76+
77+
normal: Vec2
78+
"""
79+
A unit vector pointing the way to move the first sprite to separate it
80+
from the second. Swapping the sprites flips its direction.
81+
"""
82+
83+
depth: float
84+
"""
85+
How far, in pixels, to move the first sprite along :py:attr:`normal` to
86+
separate the sprites. Always greater than zero.
87+
"""
88+
89+
6290
# Module-level aliases, so the hot path doesn't look up enum members every call
6391
_AUTO = CollisionMethod.AUTO
6492
_SPATIAL = CollisionMethod.SPATIAL
@@ -135,6 +163,120 @@ def check_for_collision(sprite1: BasicSprite, sprite2: BasicSprite) -> bool:
135163
return _check_for_collision(sprite1, sprite2)
136164

137165

166+
def get_collision_info(sprite1: BasicSprite, sprite2: BasicSprite) -> CollisionInfo | None:
167+
"""
168+
Check for a collision between two sprites, and find how to separate them.
169+
170+
This works like :py:func:`check_for_collision`, but instead of ``True``
171+
it returns a :py:class:`CollisionInfo` with the smallest move that
172+
separates the sprites: the direction to move ``sprite1`` and how far.
173+
This is useful for pushing a sprite out of a wall, or bouncing::
174+
175+
info = arcade.get_collision_info(player, wall)
176+
if info:
177+
player.position += info.normal * info.depth
178+
179+
As with :py:func:`check_for_collision`, sprites that only touch don't
180+
count as colliding.
181+
182+
.. note:: After moving by exactly ``normal * depth`` the hit boxes touch,
183+
but floating point rounding can leave them overlapping by a
184+
tiny amount. Add a small extra distance if they must not
185+
overlap at all.
186+
187+
.. warning:: The result is only correct for convex hit boxes. The
188+
detailed hit box algorithm can create concave ones.
189+
190+
When more than one move is equally small, the y axis is preferred, then
191+
the x axis, then other directions, and moving up or right over moving
192+
down or left. So two identical sprites in the same place are separated
193+
by moving ``sprite1`` up.
194+
195+
Args:
196+
sprite1: The sprite to separate
197+
sprite2: The sprite to separate it from
198+
199+
Returns:
200+
A :py:class:`CollisionInfo` if the sprites collide, otherwise ``None``.
201+
"""
202+
if __debug__:
203+
if not isinstance(sprite1, BasicSprite):
204+
raise TypeError("Parameter 1 is not an instance of a Sprite class.")
205+
if isinstance(sprite2, SpriteSequence):
206+
raise TypeError(
207+
"Parameter 2 is a instance of the SpriteList instead of a required "
208+
"Sprite. A list isn't supported here; check each sprite in it instead."
209+
)
210+
elif not isinstance(sprite2, BasicSprite):
211+
raise TypeError("Parameter 2 is not an instance of a Sprite class.")
212+
213+
hit_box1 = sprite1._hit_box
214+
hit_box2 = sprite2._hit_box
215+
216+
# Quick check with circles around each hit box, as in _check_for_collision
217+
radius1 = hit_box1._radius
218+
if radius1 is None:
219+
radius1 = hit_box1._get_radius()
220+
radius2 = hit_box2._radius
221+
if radius2 is None:
222+
radius2 = hit_box2._get_radius()
223+
radius_sum = radius1 + radius2
224+
diff_x = sprite1._position[0] - sprite2._position[0]
225+
diff_y = sprite1._position[1] - sprite2._position[1]
226+
if diff_x * diff_x + diff_y * diff_y > radius_sum * radius_sum:
227+
return None
228+
229+
points1 = hit_box1.get_adjusted_points()
230+
points2 = hit_box2.get_adjusted_points()
231+
if not points1 or not points2:
232+
return None
233+
234+
left1, right1, bottom1, top1 = hit_box1.get_adjusted_bounds()
235+
left2, right2, bottom2, top2 = hit_box2.get_adjusted_bounds()
236+
if right1 <= left2 or right2 <= left1 or top1 <= bottom2 or top2 <= bottom1:
237+
return None
238+
239+
# Find the smallest overlap. The y and x axes come from the bounds, then
240+
# the hit boxes' other edge directions. For each axis there are two
241+
# ways to move: in the positive direction (sprite1 past the top of
242+
# sprite2's range) or the negative one. Ties keep the earlier choice.
243+
up = top2 - bottom1
244+
down = top1 - bottom2
245+
if up <= down:
246+
best_depth, best_x, best_y = up, 0.0, 1.0
247+
else:
248+
best_depth, best_x, best_y = down, 0.0, -1.0
249+
250+
right = right2 - left1
251+
left = right1 - left2
252+
if right < best_depth and right <= left:
253+
best_depth, best_x, best_y = right, 1.0, 0.0
254+
elif left < best_depth and left < right:
255+
best_depth, best_x, best_y = left, -1.0, 0.0
256+
257+
axes = hit_box1._get_axes() | hit_box2._get_axes()
258+
for normal_x, normal_y in axes.values():
259+
projected_1 = [normal_x * px + normal_y * py for px, py in points1]
260+
projected_2 = [normal_x * px + normal_y * py for px, py in points2]
261+
min_1 = min(projected_1)
262+
max_1 = max(projected_1)
263+
min_2 = min(projected_2)
264+
max_2 = max(projected_2)
265+
if max_1 <= min_2 or max_2 <= min_1:
266+
return None
267+
268+
# The normals aren't unit length, so convert the overlaps to pixels
269+
length = hypot(normal_x, normal_y)
270+
positive = (max_2 - min_1) / length
271+
negative = (max_1 - min_2) / length
272+
if positive < best_depth and positive <= negative:
273+
best_depth, best_x, best_y = positive, normal_x / length, normal_y / length
274+
elif negative < best_depth and negative < positive:
275+
best_depth, best_x, best_y = negative, -normal_x / length, -normal_y / length
276+
277+
return CollisionInfo(Vec2(best_x, best_y), best_depth)
278+
279+
138280
def _check_for_collision(sprite1: BasicSprite, sprite2: BasicSprite) -> bool:
139281
"""
140282
Check for collision between two sprites.

‎benchmarks/collisions/micro.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
import timeit
1414

1515
import arcade
16-
from arcade import check_for_collision, check_for_collision_with_list
16+
from arcade import check_for_collision, check_for_collision_with_list, get_collision_info
1717
from arcade.geometry import are_polygons_intersecting
1818

1919
R = ":resources:images/"
@@ -63,6 +63,10 @@ def bench_pairs():
6363
"are_polygons_intersecting box/box", lambda: are_polygons_intersecting(square_a, square_b)
6464
)
6565

66+
print("--- get_collision_info, same pairs")
67+
for label, (a, b) in cases.items():
68+
bench(label, lambda a=a, b=b: get_collision_info(a, b))
69+
6670

6771
def bench_changing_pairs():
6872
print("--- check_for_collision, sprites changing every call")

‎tests/unit/sprite/test_sprite_collision.py‎

Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import pytest
44

55
import arcade
6+
from pyglet.math import Vec2
67

78

89
def test_sprites_at_point():
@@ -534,6 +535,145 @@ def test_gpu_collision_flipped_sprites(window, wall_scale, bullet_scale):
534535
assert arcade.check_for_collision_with_list(bullet, walls, method=gpu) == []
535536

536537

538+
def _reference_min_overlap(sprite1, sprite2):
539+
"""Smallest overlap over the x and y axes and every edge normal, in pixels"""
540+
poly_a = sprite1.hit_box.get_adjusted_points()
541+
poly_b = sprite2.hit_box.get_adjusted_points()
542+
axes = [(1.0, 0.0), (0.0, 1.0)]
543+
for polygon in (poly_a, poly_b):
544+
for i in range(len(polygon)):
545+
(x1, y1), (x2, y2) = polygon[i], polygon[(i + 1) % len(polygon)]
546+
length = ((y2 - y1) ** 2 + (x1 - x2) ** 2) ** 0.5
547+
if length:
548+
axes.append(((y2 - y1) / length, (x1 - x2) / length))
549+
best = None
550+
for nx, ny in axes:
551+
projected_a = [nx * x + ny * y for x, y in poly_a]
552+
projected_b = [nx * x + ny * y for x, y in poly_b]
553+
overlap = min(max(projected_a) - min(projected_b), max(projected_b) - min(projected_a))
554+
best = overlap if best is None else min(best, overlap)
555+
return best
556+
557+
558+
def _random_convex_sprite(rng, textures, shared_angle):
559+
sprite = arcade.Sprite(rng.choice(textures))
560+
sprite.scale = (rng.choice([-1, 1]) * rng.choice([0.25, 0.5, 1, 1.5]),
561+
rng.choice([-1, 1]) * rng.choice([0.25, 0.5, 1, 1.5])) # fmt: skip
562+
if rng.random() < 0.5:
563+
sprite.angle = shared_angle
564+
else:
565+
sprite.angle = rng.choice([0, 0, 90, 180, 30, rng.uniform(0, 360)])
566+
sprite.position = rng.randint(-160, 160) / 2, rng.randint(-160, 160) / 2
567+
return sprite
568+
569+
570+
def test_get_collision_info_basics(window):
571+
a = arcade.SpriteSolidColor(10, 10)
572+
b = arcade.SpriteSolidColor(10, 10, center_x=8, center_y=1)
573+
# The smallest overlap is 2 pixels in x, so move a left
574+
assert arcade.get_collision_info(a, b) == (Vec2(-1.0, 0.0), 2.0)
575+
# Swapping the sprites flips the normal
576+
assert arcade.get_collision_info(b, a) == (Vec2(1.0, 0.0), 2.0)
577+
578+
# Sinking into the floor: pushed straight up by exactly the overlap
579+
player = arcade.SpriteSolidColor(10, 10, center_x=20, center_y=3)
580+
floor = arcade.SpriteSolidColor(100, 10)
581+
info = arcade.get_collision_info(player, floor)
582+
assert info.normal == Vec2(0.0, 1.0)
583+
assert info.depth == 7.0
584+
player.position += info.normal * info.depth
585+
assert player.position == (20, 10)
586+
assert arcade.check_for_collision(player, floor) is False
587+
588+
# Identical sprites in the same place: moved up
589+
assert arcade.get_collision_info(a, arcade.SpriteSolidColor(10, 10)) == (Vec2(0.0, 1.0), 10.0)
590+
591+
# Touching or apart: no collision
592+
assert arcade.get_collision_info(a, arcade.SpriteSolidColor(10, 10, center_x=10)) is None
593+
assert arcade.get_collision_info(a, arcade.SpriteSolidColor(10, 10, center_x=50)) is None
594+
595+
596+
def test_get_collision_info_diagonal(window):
597+
"""A diagonal edge gives a diagonal normal"""
598+
box = arcade.SpriteSolidColor(20, 20)
599+
box.angle = 45
600+
other = arcade.SpriteSolidColor(20, 20, center_x=12, center_y=12)
601+
info = arcade.get_collision_info(other, box)
602+
assert info.normal.x == pytest.approx(2**-0.5)
603+
assert info.normal.y == pytest.approx(2**-0.5)
604+
assert info.depth == pytest.approx(_reference_min_overlap(other, box))
605+
606+
607+
def test_get_collision_info_type_errors(window):
608+
a = arcade.SpriteSolidColor(10, 10)
609+
with pytest.raises(TypeError):
610+
arcade.get_collision_info("moo", a)
611+
with pytest.raises(TypeError):
612+
arcade.get_collision_info(a, "moo")
613+
with pytest.raises(TypeError):
614+
arcade.get_collision_info(a, arcade.SpriteList())
615+
616+
617+
def test_get_collision_info_matches_check_for_collision(window):
618+
"""It finds a collision exactly when check_for_collision does, for any hit box"""
619+
rng = random.Random(77)
620+
textures = [
621+
arcade.load_texture(":resources:images/tiles/grassMid.png"),
622+
arcade.load_texture(":resources:images/items/coinGold.png"),
623+
arcade.load_texture(":resources:images/space_shooter/laserBlue01.png"),
624+
arcade.load_texture(
625+
":resources:images/space_shooter/meteorGrey_big1.png",
626+
hit_box_algorithm=arcade.hitbox.algo_detailed,
627+
),
628+
]
629+
results = {True: 0, False: 0}
630+
for _ in range(3000):
631+
shared_angle = rng.choice([0, 90, 180, 45, 30, rng.uniform(0, 360)])
632+
a = _random_convex_sprite(rng, textures, shared_angle)
633+
b = _random_convex_sprite(rng, textures, shared_angle)
634+
expected = arcade.check_for_collision(a, b)
635+
assert (arcade.get_collision_info(a, b) is not None) is expected
636+
assert (arcade.get_collision_info(b, a) is not None) is expected
637+
results[expected] += 1
638+
assert min(results.values()) > 300
639+
640+
641+
def test_get_collision_info_separates(window):
642+
"""For convex hit boxes, moving by normal * depth is the smallest move that separates them"""
643+
rng = random.Random(78)
644+
textures = [
645+
arcade.load_texture(":resources:images/tiles/grassMid.png"),
646+
arcade.load_texture(":resources:images/items/coinGold.png"),
647+
arcade.load_texture(":resources:images/space_shooter/laserBlue01.png"),
648+
arcade.load_texture(
649+
":resources:images/animated_characters/female_person/femalePerson_idle.png"
650+
),
651+
]
652+
checked = 0
653+
for _ in range(3000):
654+
shared_angle = rng.choice([0, 90, 180, 45, 30, rng.uniform(0, 360)])
655+
a = _random_convex_sprite(rng, textures, shared_angle)
656+
b = _random_convex_sprite(rng, textures, shared_angle)
657+
info = arcade.get_collision_info(a, b)
658+
if info is None:
659+
continue
660+
checked += 1
661+
assert info.depth > 0
662+
assert info.normal.length() == pytest.approx(1.0)
663+
assert info.depth == pytest.approx(_reference_min_overlap(a, b), abs=1e-6)
664+
665+
start = a.position
666+
# A little further than depth separates them
667+
a.position = start + info.normal * (info.depth + 1e-6)
668+
assert arcade.check_for_collision(a, b) is False
669+
# A little less doesn't
670+
if info.depth > 1e-5:
671+
a.position = start + info.normal * (info.depth - 1e-6)
672+
assert arcade.check_for_collision(a, b) is True
673+
a.position = start
674+
assert checked > 300
675+
676+
537677
def test_check_for_collision_with_list(window):
538678
# TODO: Check that the right collision function is called internally
539679
a = arcade.SpriteSolidColor(50, 50, color=arcade.csscolor.RED)

0 commit comments

Comments
 (0)