Skip to content

Commit

Permalink
Factor out sprite towards/away from logic
Browse files Browse the repository at this point in the history
  • Loading branch information
ccntrq committed Feb 15, 2023
1 parent a7b408c commit d83e4b7
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 22 deletions.
15 changes: 4 additions & 11 deletions src/sprite/enemy.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import random

import config
from util.direction import DirectionUtil


class EnemySprite(arcade.Sprite):
Expand All @@ -20,15 +21,7 @@ def __init__(self):
self.texture = arcade.load_texture(image_source)

def away_from(self, sprite):
start_x = self.center_x
start_y = self.center_y
dir = DirectionUtil.away_from(self, sprite)

dest_x = sprite.center_x
dest_y = sprite.center_y

x_diff = dest_x - start_x
y_diff = dest_y - start_y
angle = math.atan2(y_diff, x_diff)

self.change_x = -1 * math.cos(angle) * config.ENEMY_MAX_SPEED / 2
self.change_y = -1 * math.sin(angle) * config.ENEMY_MAX_SPEED / 2
self.change_x = dir[0] * config.ENEMY_MAX_SPEED / 2
self.change_y = dir[1] * config.ENEMY_MAX_SPEED / 2
15 changes: 15 additions & 0 deletions src/util/direction.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import math


class DirectionUtil:
@staticmethod
def towards(start, target):
x_diff = target.center_x - start.center_x
y_diff = target.center_y - start.center_y
angle = math.atan2(y_diff, x_diff)

return (math.cos(angle), math.sin(angle))

@staticmethod
def away_from(start, target):
return DirectionUtil.towards(target, start)
15 changes: 4 additions & 11 deletions src/view/game.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from sprite.heart import HeartSprite
from sprite.pliers import PliersSprite
from sprite.tooth import ToothSprite
from util.direction import DirectionUtil
from view.game_over import GameOverView


Expand Down Expand Up @@ -594,15 +595,7 @@ def random_y(self):
)

def position_after_hit(self, player, enemy, sprite):
start_x = player.center_x
start_y = player.center_y
dest = DirectionUtil.towards(player, enemy)

dest_x = enemy.center_x
dest_y = enemy.center_y

x_diff = dest_x - start_x
y_diff = dest_y - start_y
angle = math.atan2(y_diff, x_diff)

sprite.center_x = enemy.center_x + math.cos(angle) * 128
sprite.center_y = enemy.center_y + math.sin(angle) * 128
sprite.center_x = enemy.center_x + dest[0] * 128
sprite.center_y = enemy.center_y + dest[0] * 128

0 comments on commit d83e4b7

Please sign in to comment.