The helicopter should fly according to angle 1. when a key is pressed, it should fly according to angle 2. It is working. With angle 1 = 0 the helicopter flies parallel to the x axis. The helicopter image also shows this. With angle 2 = 45 it goes diagonally down. But the picture shows diagonally upwards. How can I reconcile angle and image rotation?
import pygame, sys
import random
import math
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((1000,600))
class Helikopter(pygame.sprite.Sprite):
def __init__(self,x,y,speed,angle1,angle2):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("Bilder/heli1.png").convert_alpha()
self.img = pygame.transform.scale(self.image,(160,60))
self.rect = self.img.get_rect()
self.rect.center=(x,y)
self.rot1 = angle1
self.rot2 = angle2
self.angle1 = math.radians(angle1)
self.angle2 = math.radians(angle2)
self.rot = self.rot1
self.angle = self.angle1
self.speed = speed
self.absturz = False
def update(self):
if self.rect.x > 1000 or self.rect.y > 600:
self.rect.x = - 20
self.rect.y = random.randrange(100,300)
self.absturz = False
self.rot = self.rot1
self.angle = self.angle1
if self.absturz == True:
self.angle = self.angle2
self.rot = self.rot2 - 45
else:
self.absturz = False
self.rect.center=calculate_new_xy(self.rect.center,self.speed,self.angle)
self.image = pygame.transform.rotate(self.img, self.rot)
def calculate_new_xy(old_xy,speed,angle_in_radians):
new_x = old_xy[0] (speed*math.cos(angle_in_radians))
new_y = old_xy[1] (speed*math.sin(angle_in_radians))
return new_x, new_y
heli = Helikopter(300,100,3,30,60)
alle_sprites = pygame.sprite.Group()
heli_sprites = pygame.sprite.Group()
heli = Helikopter(300,100,3,0,90)
heli_sprites.add(heli)
alle_sprites.add(heli)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
heli.absturz = True
screen.fill((250,250,250))
alle_sprites.update()
alle_sprites.draw(screen)
pygame.display.flip()
clock.tick(60)
CodePudding user response:
In the Pygame coordinate system the y-axis points down the screen, but the mathematical y axis points form the bottom to the top. To compansate that you have to invert the angle of rotation when you call pygame.transform.rotate
:
self.image = pygame.transform.rotate(self.img, self.rot)
self.image = pygame.transform.rotate(self.img, -self.rot)
Also see How do I rotate an image around its center using PyGame?