Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,11 @@ Arcade [PyPi Release History](https://pypi.org/project/arcade/#history) page.
### New Features
- Added `HitBox.get_adjusted_bounds()`, which returns the cached `(left, right, bottom, top)` bounds of the adjusted hit box points.
- 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.
- 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.
- 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.

### Misc Changes
- The platformer and simple physics engines and `AStarBarrierList` now use `has_collision_with_list(s)` where they only need to know whether there's a collision. Building an `AStarBarrierList` is about 7-9% faster.
- Sped up sprite collision checks. Sprites that pass the quick distance check are now compared by cached hit box bounds before the polygon test, and the polygon test skips horizontal and vertical edges, which the bounds check already covers. Checks that reach the polygon test are about 2-4x faster, e.g. 8.0 to 2.3 µs for two box hit boxes and 21.6 to 10.2 µs for two default octagon hit boxes. `are_polygons_intersecting` is also faster (7.3 to 1.6 µs for two rectangles).
- Sped up collision checks further by caching each hit box's distinct edge directions. Parallel edges (such as opposite sides of the default octagon hit boxes, or matching edges on two sprites with the same angle) are only tested once, and the cache is kept when a sprite moves. Two unrotated octagon hit boxes go from 12.0 to 4.6 µs, and two rotated 30° from 20.8 to 6.9 µs.
- `SpatialHash` now uses the hit box's cached bounds to find a sprite's grid cells, so they're shared with collision checks. Adding, removing, and querying for sprites that haven't moved is about 33-40% faster.
Expand Down
6 changes: 6 additions & 0 deletions arcade/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,9 @@ def configure_logging(level: int | None = None):
from .sprite_list import check_for_collision
from .sprite_list import check_for_collision_with_list
from .sprite_list import check_for_collision_with_lists
from .sprite_list import check_for_collision_between_lists
from .sprite_list import has_collision_with_list
from .sprite_list import has_collision_with_lists
from .sprite_list import get_closest_sprite
from .sprite_list import get_sprites_at_exact_point
from .sprite_list import get_sprites_at_point
Expand Down Expand Up @@ -330,6 +333,9 @@ def configure_logging(level: int | None = None):
"check_for_collision",
"check_for_collision_with_list",
"check_for_collision_with_lists",
"check_for_collision_between_lists",
"has_collision_with_list",
"has_collision_with_lists",
"close_window",
"disable_timings",
"draw_arc_filled",
Expand Down
11 changes: 4 additions & 7 deletions arcade/paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
BasicSprite,
Sprite,
SpriteSequence,
check_for_collision_with_list,
has_collision_with_list,
get_sprites_at_point,
)
from arcade.math import get_distance, lerp_2d
Expand All @@ -33,9 +33,9 @@ def _spot_is_blocked(
"""
original_pos = moving_sprite.position
moving_sprite.position = position
hit_list = check_for_collision_with_list(moving_sprite, blocking_sprites)
hit = has_collision_with_list(moving_sprite, blocking_sprites)
moving_sprite.position = original_pos
return len(hit_list) > 0
return hit


def _heuristic(start: Point2, goal: Point2) -> float:
Expand Down Expand Up @@ -319,10 +319,7 @@ def recalculate(self):

# See if we'll have a collision if our sprite is at this location
self.moving_sprite.position = pos
if (
len(check_for_collision_with_list(self.moving_sprite, self.blocking_sprites))
> 0
):
if has_collision_with_list(self.moving_sprite, self.blocking_sprites):
self.barrier_list.add(cpos)

# Restore original location
Expand Down
24 changes: 8 additions & 16 deletions arcade/physics_engines.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
SpriteType,
check_for_collision,
check_for_collision_with_lists,
has_collision_with_lists,
)
from arcade.math import get_distance

Expand Down Expand Up @@ -71,10 +72,7 @@ def _wiggle_until_free(colliding: Sprite, walls: Iterable[SpriteSequence[BasicSp
for strided_index in range(0, 16, 2):
x, y = try_list[strided_index:strided_index + 2]
colliding.position = x, y
check_hit_list = check_for_collision_with_lists(colliding, walls)
# print(f"Vary {vary} ({trapped.center_x} {trapped.center_y}) "
# f"= {len(check_hit_list)}")
if len(check_hit_list) == 0:
if not has_collision_with_lists(colliding, walls):
return
wiggle_distance *= 2

Expand Down Expand Up @@ -104,7 +102,7 @@ def _move_sprite(
collided with.
"""
# See if we are starting this turn with a sprite already colliding with us.
if len(check_for_collision_with_lists(moving_sprite, can_collide)) > 0:
if has_collision_with_lists(moving_sprite, can_collide):
_wiggle_until_free(moving_sprite, can_collide)

original_x, original_y = moving_sprite.position
Expand Down Expand Up @@ -143,7 +141,7 @@ def _move_sprite(
# If we hit a wall, move so the edges are at the same point
if len(hit_list_x) > 0:
if moving_sprite.change_y > 0:
while len(check_for_collision_with_lists(moving_sprite, can_collide)) > 0:
while has_collision_with_lists(moving_sprite, can_collide):
moving_sprite.center_y -= 1
# print(f"Spot X ({self.player_sprite.center_x}, {self.player_sprite.center_y})"
# f" {self.player_sprite.change_y}")
Expand Down Expand Up @@ -645,9 +643,7 @@ def is_on_ladder(self) -> bool:
:py:attr:`ladders`.
"""
if self.ladders:
hit_list = check_for_collision_with_lists(self.player_sprite, self.ladders)
if len(hit_list) > 0:
return True
return has_collision_with_lists(self.player_sprite, self.ladders)
return False

def can_jump(self, y_distance: float = 5) -> bool:
Expand Down Expand Up @@ -686,18 +682,14 @@ def can_jump(self, y_distance: float = 5) -> bool:

# Temporarily move the player down to collide floor-like sprites
self.player_sprite.center_y -= y_distance
hit_list = check_for_collision_with_lists(self.player_sprite, self._all_obstacles)
on_ground = has_collision_with_lists(self.player_sprite, self._all_obstacles)
self.player_sprite.center_y += y_distance

# Reset the number jumps if the player touched a floor-like sprite
if len(hit_list) > 0:
if on_ground:
self.jumps_since_ground = 0

if (
len(hit_list) > 0
or self.allow_multi_jump
and self.jumps_since_ground < self.allowed_jumps
):
if on_ground or self.allow_multi_jump and self.jumps_since_ground < self.allowed_jumps:
return True
else:
return False
Expand Down
6 changes: 6 additions & 0 deletions arcade/sprite_list/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
check_for_collision,
check_for_collision_with_list,
check_for_collision_with_lists,
check_for_collision_between_lists,
has_collision_with_list,
has_collision_with_lists,
get_sprites_at_point,
get_sprites_at_exact_point,
get_sprites_in_rect,
Expand All @@ -23,6 +26,9 @@
"check_for_collision",
"check_for_collision_with_list",
"check_for_collision_with_lists",
"check_for_collision_between_lists",
"has_collision_with_list",
"has_collision_with_lists",
"get_sprites_at_point",
"get_sprites_at_exact_point",
"get_sprites_in_rect",
Expand Down
148 changes: 148 additions & 0 deletions arcade/sprite_list/collision.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from collections.abc import Iterable
from enum import IntEnum
from typing import TypeVar

from arcade.geometry import (
_are_polygons_overlapping_on_axes,
Expand All @@ -14,6 +15,9 @@

from .sprite_list import SpriteSequence

# The sprite type of the second list in check_for_collision_between_lists
_SpriteType2 = TypeVar("_SpriteType2", bound=BasicSprite)


class CollisionMethod(IntEnum):
"""
Expand Down Expand Up @@ -259,6 +263,150 @@ def check_for_collision_with_list(
# collision_list.append(sprite2)


def has_collision_with_list(
sprite: BasicSprite,
sprite_list: SpriteSequence[BasicSprite],
method: CollisionMethod | int = CollisionMethod.AUTO,
) -> bool:
"""
Check if a sprite collides with any sprite in a list.

This is faster than checking whether :py:func:`check_for_collision_with_list`
returns an empty list, since it stops at the first collision it finds.

Args:
sprite:
Sprite to check
sprite_list:
SpriteList to check against
method:
How to find the sprites to check. See :py:class:`CollisionMethod`.
Defaults to :py:attr:`CollisionMethod.AUTO`.

Returns:
``True`` if the sprite collides with at least one sprite in the list.
"""
if __debug__:
if not isinstance(sprite, BasicSprite):
raise TypeError(
f"Parameter 1 is not an instance of the Sprite class, "
f"it is an instance of {type(sprite)}."
)
if not isinstance(sprite_list, SpriteSequence):
raise TypeError(f"Parameter 2 is a {type(sprite_list)} instead of expected SpriteList.")

for sprite2 in _get_sprites_to_check(sprite, sprite_list, method):
if sprite is not sprite2 and _check_for_collision(sprite, sprite2):
return True
return False


def has_collision_with_lists(
sprite: BasicSprite,
sprite_lists: Iterable[SpriteSequence[BasicSprite]],
method: CollisionMethod | int = CollisionMethod.AUTO,
) -> bool:
"""
Check if a sprite collides with any sprite in any of several lists.

This is faster than checking whether :py:func:`check_for_collision_with_lists`
returns an empty list, since it stops at the first collision it finds.

Args:
sprite:
Sprite to check
sprite_lists:
SpriteLists to check against
method:
How to find the sprites to check. See :py:class:`CollisionMethod`.
Defaults to :py:attr:`CollisionMethod.AUTO`.

Returns:
``True`` if the sprite collides with at least one sprite in the lists.
"""
if __debug__:
if not isinstance(sprite, BasicSprite):
raise TypeError(
f"Parameter 1 is not an instance of the BasicSprite class, "
f"it is an instance of {type(sprite)}."
)

for sprite_list in sprite_lists:
for sprite2 in _get_sprites_to_check(sprite, sprite_list, method):
if sprite is not sprite2 and _check_for_collision(sprite, sprite2):
return True
return False


def check_for_collision_between_lists(
sprite_list_a: SpriteSequence[SpriteType],
sprite_list_b: SpriteSequence[_SpriteType2],
method: CollisionMethod | int = CollisionMethod.AUTO,
) -> list[tuple[SpriteType, _SpriteType2]]:
"""
Find every pair of colliding sprites between two lists.

For example, to remove bullets and the enemies they hit::

for bullet, enemy in arcade.check_for_collision_between_lists(bullets, enemies):
bullet.remove_from_sprite_lists()
enemy.remove_from_sprite_lists()

A sprite can be in more than one pair, such as a bullet hitting two
enemies at once.

For each sprite in ``sprite_list_a``, ``method`` chooses how to find the
sprites in ``sprite_list_b`` to check, the same way as in
:py:func:`check_for_collision_with_list`. For the best speed, enable
spatial hashing on ``sprite_list_b``, and make it the list whose sprites
move less.

If both arguments are the same list, each colliding pair is returned
once, and sprites are never paired with themselves.

Args:
sprite_list_a:
The first list of sprites
sprite_list_b:
The second list of sprites
method:
How to find the sprites in ``sprite_list_b`` to check. See
:py:class:`CollisionMethod`. Defaults to :py:attr:`CollisionMethod.AUTO`.

Returns:
A list of ``(sprite_a, sprite_b)`` tuples, or an empty list.
"""
if __debug__:
if not isinstance(sprite_list_a, SpriteSequence):
raise TypeError(
f"Parameter 1 is a {type(sprite_list_a)} instead of expected SpriteList."
)
if not isinstance(sprite_list_b, SpriteSequence):
raise TypeError(
f"Parameter 2 is a {type(sprite_list_b)} instead of expected SpriteList."
)

pairs: list[tuple[SpriteType, _SpriteType2]] = []
if not sprite_list_a or not sprite_list_b:
return pairs

if sprite_list_a is sprite_list_b:
# Only report each pair once, by skipping sprites already checked
checked: set[BasicSprite] = set()
for sprite_a in sprite_list_a:
checked.add(sprite_a)
for sprite_b in _get_sprites_to_check(sprite_a, sprite_list_b, method):
if sprite_b not in checked and _check_for_collision(sprite_a, sprite_b):
pairs.append((sprite_a, sprite_b))
return pairs

for sprite_a in sprite_list_a:
for sprite_b in _get_sprites_to_check(sprite_a, sprite_list_b, method):
if sprite_a is not sprite_b and _check_for_collision(sprite_a, sprite_b):
pairs.append((sprite_a, sprite_b))
return pairs


def check_for_collision_with_lists(
sprite: BasicSprite,
sprite_lists: Iterable[SpriteSequence[SpriteType]],
Expand Down
Loading
Loading