user2975896
user2975896

Reputation: 85

Angular Movement in Python/Pygame

Me and a few friends are messing around with a new shooting mechanic. The idea is if you click left mouse button, your character rotates left, if you click right, the player rotates right, and if you click both, the player goes backwards. Here is our code:

if char_image_number == (0, 0, 0):
        char_image = pygame.image.load(player_none).convert_alpha()
        char_image = pygame.transform.rotate(char_image, angle)

        screen.blit(char_image,(540, 260))
        pygame.display.update()

elif char_image_number == (1, 0, 0):
        print (angle)
        char_image = pygame.image.load(player_left).convert_alpha()
        angle+=1
        char_image = pygame.transform.rotate(char_image, angle)
        bullets.append(
        screen.blit(char_image,(540, 260))
        pygame.display.update()

elif char_image_number == (0, 0, 1):
        print (angle)
        angle-=1
        char_image = pygame.image.load(player_right).convert_alpha()
        char_image=pygame.transform.rotate(char_image, angle)

        screen.blit(char_image,(540, 260))

        pygame.display.update()
elif char_image_number == (1, 0, 1):
        char_image = pygame.image.load(player_both).convert_alpha()
        char_image = pygame.transform.rotate(char_image, angle)

        screen.blit(char_image,(540, 260))
        pygame.display.update()

How would we be able to make it go backwards, from the current angle it is facing?

Upvotes: 0

Views: 608

Answers (1)

johannestaas
johannestaas

Reputation: 1225

This is a math problem. Any offset to push the image backwards is going to be a composite offset of x and y. This takes trigonometry to figure out.

In trig, sin(angle) = delta_y / distance_moved in your case.

and

cos(angle) = delta_x / distance_moved

What you need to do is take distance_moved, how many pixels you want the image to travel every frame, and multiply that by the sin or cos of the angle. That will figure out the change in y and x you need to offset the sprite by.

In Python and many other languages, you will need the angle in radians (pretty standard unit). This mathematical unit represents 180 degrees in one Pi . To convert degrees to radians, you divide by 180 and multiply by Pi.

In Python:

import math

def convert_degrees(degrees):
    return degrees / 180.0 * math.pi

Examples of sin and cos:

import math
example = 2.0 * math.sin(math.pi) 
example2 = 3.0 * math.cos(convert_degrees(120))

I'll leave the rest to you to figure out.

Upvotes: 1

Related Questions