Sign in to follow this  

8 directional steering with pygame

This topic is 3730 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

OK, so I'm supposed to do a little game for a project in school. However I've got a minor issue, I can't get the steering of my cute little spaceship to work according to my plans. Thing is I want 8 directional steering, but I really don't know how to do it. Right now 4 directions work fine with this code: elif event.type == KEYDOWN: if event.key == K_ESCAPE: self.exit = True elif event.key == K_UP: self.state.angle = 270 elif event.key == K_DOWN: self.state.angle = 90 elif event.key == K_LEFT: self.state.angle = 180 elif event.key == K_RIGHT: self.state.angle = 0 But what I want to be able to do is to have let's say the right arrow key pressed and then pressing maybe the up arrow key and the little devil should be travelling to the north east instead. How can I do this? Thank you in advance, Papa Z

Share this post


Link to post
Share on other sites
Treat your keys as switches, then use their states to determine direction once per game loop:


d = {( 1, 1) : 45, # SE
( 0, 1) : 90, # S
(-1, 1) : 135, # SW
(-1, 0) : 180, # W
(-1,-1) : 225, # NW
( 0,-1) : 270, # N
( 1,-1) : 315, # NE
( 1, 0) : 360 } # E
x_dir = 0
y_dir = 0

...

while True: # game loop
...

evt = pygame.event.poll()
...
# other events
...

elif evt.type == KEYDOWN:
if evt.key == K_UP:
y_dir = -1
elif evt.key == K_DOWN:
y_dir = 1
elif evt.key == K_LEFT:
x_dir = -1
elif evt.key == K_RIGHT:
x_dir = 1
...

elif evt.type == KEYUP:
if evt.key == K_UP:
y_dir = 0
elif evt.key == K_DOWN:
y_dir = 0
elif evt.key == K_LEFT:
x_dir = 0
elif evt.key == K_RIGHT:
x_dir = 0
...

...
# other events
...

self.state.angle = d[(x_dir,y_dir)]


Share this post


Link to post
Share on other sites

This topic is 3730 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this