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 problem with the image or something, but any help would be appreciated. Just in case you don't know, direction is calculated by taking the difference between the mouse pos and image pos, running it through the atan function, dividing it by 6.28, and then multiplying by 360. This will result in the degree your mouse it at from the image. Here's the code. Also, I'm supposed to attribute the developer of the image, so here. Icons made by mynamepong from www.flaticon.com
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)
carx=200
cary=200
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
win.fill(black)
car_rotated=pygame.transform.rotate(car,angle)
win.blit(car_rotated,(carx,cary))
pygame.display.update()
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