How To Make An Image In Pygame Stay Still When Rotated?
So I'm trying to make an image point towards the mouse at all times, and it sorta works. The image points towards the mouse, but it's moving around a bit. I don't know if it is a p
Solution 1:
You need to set the car center then rotate the car around that point.
Try this code:
import pygame
import math
pygame.init()
win_height=800
win_width=800
win=pygame.display.set_mode((win_width,win_height))
pygame.display.set_caption("Rotation Test")
black=(0,0,0)
# center of car rect
carx=400
cary=400
clock=pygame.time.Clock()
car=pygame.image.load("inkscape images for games/car.png")
car=pygame.transform.scale(car,(100,100))
while True:
mouse=pygame.mouse.get_pos()
clock.tick(60)
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
angle=math.atan2(mouse[0]-carx,mouse[1]-cary)/6.28*360-90
win.fill(black)
car_rotated=pygame.transform.rotate(car,angle)
new_rect = car_rotated.get_rect(center = (carx, cary))
win.blit(car_rotated,(new_rect.x,new_rect.y))
pygame.display.update()
Output
Solution 2:
It looks like pygame moves the image if you rotate it at any angle other than a right angle. To get around this you'll have to keep track of the previous center position of the image and update it every frame. Try something like this:
car_rotated=pygame.transform.rotate(car,angle)
new_rect = car_rotated.get_rect(center = car.get_rect().center)
win.blit(car_rotated,new_rect)
The code looked like it was rotating correctly when I tested it, but it still looked a little weird for some reason. Let me know if this is what you're going for.
Post a Comment for "How To Make An Image In Pygame Stay Still When Rotated?"