Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
554 views
in Technique[技术] by (71.8m points)

python - Changing direction of rotation Pygame

How would you change the direction of a rotating image/rect in Pygame? Applying positive and negative degree values works but it seems to only be able to rotate one direction throughout my window. Is there a way to ensure a change in direction of rotation?


Perhaps change up rotation of a spinning image every 5 seconds, or if able to change the direction of the spin when hitting a X or Y axis. I've added some code below.

It seems like switching movement directions is easy with rect.move_ip as long as I specify a speed and have location clause, it does what I want. Unfortunately rotation is't like that. Here I'l adding angles to make sure it spins, but no matter what I try, I'm unable to negate the rotation.


def rotate_image(self):  #rotate image
    orig_rect = self.image.get_rect()
    rot_image = pygame.transform.rotate(self.image, self.angle)
    rot_rect = orig_rect.copy()
    rot_rect.center = rot_image.get_rect().center
    rot_image = rot_image.subsurface(rot_rect).copy()
    return rot_image

def render(self):
    self.screen.fill(self.bg_color)
    self.rect.move_ip(0,5)                 #Y axis movement at 5 px per frame
    self.angle += 5             #add 5 anglewhen the rect has not hit one of the window
    self.angle %= 360

    if self.rect.left < 0 or self.rect.right > self.width:         
        self.speed[0] = -self.speed[0]
        self.angle = -self.angle           #tried to invert the angle 
        self.angle -= 5                    #trying to negate the angle rotation
        self.angle %= 360

    self.screen.blit(self.rotate_image(),self.rect)
    pygame.display.flip()

I would really like to know how to invert rotation of a image. You may provide your own examples.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As far as I know, there is only one way of rotating the image using

    pygame.transform.rotate(surface, angle)

You can check the official documentation

http://www.pygame.org/docs/ref/transform.html Here is the example code:-

    screen = pygame.display.set_mode((640,480))
    surf = pygame.image.load("/home/image.jpeg").convert()
    while True:
       newsurf = pygame.transform.rotate(surf, -90)
       screen.blit(newsurf, (100,100))
       pygame.display.flip()
       time.sleep(2)

This code will keep on rotating the image after every 2 seconds by 90 degrees in clockwise direction. Hope this helps..


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...