Created
September 17, 2018 18:14
-
-
Save RichardMarks/85d33aa0177891b582d1e729e4283364 to your computer and use it in GitHub Desktop.
normalized 8-directional sprite movement using lookup tables
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def move_sprite(sprite, dt, key_up, key_down, key_left, key_right): | |
""" | |
returns the x and y tuple offset for normalized 8-directional movement | |
sprite is expected to have x, y, x_speed, and y_speed properties | |
speed is expected to be represented in pixels per second | |
""" | |
# Note: using legacy "mm" and "mt" variable names | |
# whose original meaning has been forgotten over the last 20 years | |
mm = [0, 0, 1, 3, 1, 2, 0, 0, 3, 1, 5, 5, 5, 4, 0, 0, 2, 1, 4, 5, 4, 4] | |
mt = [0, 0.0, 1.0, -1.0, 0.7071067811865475, -0.7071067811865475] | |
control_code = 0 | |
if key_up: | |
control_code = control_code | 2 | |
elif key_down: | |
control_code = control_code | 4 | |
if key_left: | |
control_code = control_code | 8 | |
elif key_right: | |
control_code = control_code | 16 | |
if control_code > 0: | |
# find the directional movement using lookup tables | |
mx = mt[mm[control_code]] * sprite.x_speed | |
my = mt[mm[control_code + 1]] sprite.y_speed | |
next_x = sprite.x + mx * dt | |
next_y = sprite.y + my * dt | |
return (next_x, next_y) | |
else: | |
# no change in position | |
return (sprite.x, sprite.y) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment