Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add move_towards fct in Actor #277

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
20 changes: 20 additions & 0 deletions pgzero/actor.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import annotations
import pygame
from math import radians, sin, cos, atan2, degrees, sqrt

Expand All @@ -6,6 +7,9 @@
from . import rect
from . import spellcheck

from typing import Sequence, Tuple, Union
from pygame import Vector2
_Coordinate = Union[Tuple[float, float], Sequence[float], Vector2]

ANCHORS = {
'x': {
Expand Down Expand Up @@ -361,5 +365,21 @@ def distance_to(self, target):
dy = ty - myy
return sqrt(dx * dx + dy * dy)

def move_towards(self, direction: Union[int, float, Actor, _Coordinate],
distance, stop_on_target=True):
"""move actor position of a certain distance in pixels in a certain direction.
this direction can be an angle in degrees or an Actor or a coordinate"""
if isinstance(direction, (int, float)):
angle = radians(direction)
else:
angle = radians(self.angle_to(direction))
if stop_on_target:
target_distance = self.distance_to(direction)
if (target_distance < distance) and distance > 0:
distance = target_distance
dx = distance * cos(angle)
dy = -distance * sin(angle)
self.pos = (self.x + dx, self.y + dy)

def unload_image(self):
loaders.images.unload(self._image_name)