I have a character in PyGame which I want to move forward depending on its rotation. Currently it's very strange and wonky.
CodePudding user response:
import pygame, math
pygame.init()
size = width, height = 600, 600
green = 50, 168, 82
screen = pygame.display.set_mode(size)
class Capybara:
def __init__(self, size_multiplier):
self.capybara = pygame.image.load('capybara.png')
self.o_size = 92, 206
self.new_size = (self.o_size[0] * size_multiplier,self.o_size[1] * size_multiplier)
self.capybara = pygame.transform.scale(self.capybara, self.new_size)
self.base_capybara = self.capybara
self.rotation = 0
self.x, self.y = 300, 300
self.rect = self.capybara.get_rect(center = (round(self.x), round(self.y)))
def rotate(self, amount):
self.rotation = amount
if self.rotation > 360:
self.rotation -= 360
elif self.rotation < 0:
self.rotation = 360
self.capybara = pygame.transform.rotate(self.base_capybara, self.rotation)
self.rect = self.capybara.get_rect(center = (round(self.x), round(self.y)))
def move(self, move):
self.x = move * math.cos(math.radians(self.rotation 90))
self.y -= move * math.sin(math.radians(self.rotation 90))
capybara = Capybara(0.8)
fpsClock = pygame.time.Clock()
rotate_l = False
rotate_r = False
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
keys = pygame.key.get_pressed()
rotate = keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]
move = keys[pygame.K_DOWN] - keys[pygame.K_UP]
capybara.move(-move * 5)
capybara.rotate(-rotate)
screen.fill(green)
screen.blit(capybara.capybara, capybara.rect)
pygame.display.update()
fpsClock.tick(60)