1

I've seen fixes to this problem elsewhere on StackOverflow, but I'm too new to this language to apply them to mine.

I'm making a Surface, drawing stuff on it, and then rotating it. The result is the same as this guy's issue:

The rectangle moves erratically as it rotates. Is this fixable, or must I change my approach?

from pygame import * 
import sys

def drawShip(pos,angle,width,height,surface):   

    canvas = Surface((width,height))#A canvas to draw the ship on

    r = ((1),(1),width,height)#A placeholder rectangle
    draw.rect(canvas,(255,0,0),r)#Draw r on the surface

    canvas = transform.rotate(canvas,angle)#Rotate the canvas

    surface.blit(canvas,((pos[0] - width/2),(pos[1] - height/2)))#Draw the canvas onto the main surface        

s = display.set_mode((500,500))#Create the main surface   
i = 0

while True:
    for e in event.get():
            if e.type == QUIT:
                sys.exit()
            if e.type == KEYDOWN:
                i += 5
    drawShip((250,250),i,100,100,s)#Draw a ship
    display.flip()#Update the display
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
CapnCheesy
  • 13
  • 5

1 Answers1

1

See How do I rotate an image around its center using Pygame?.

Get a rectangle with the size of the rotated Surface by get_rect() and set the center of the rectangle to the desired position by an key word argument. Use the rectangle to draw the Surface. The 2nd argument of blit can be a Rect object, which specifies the destination location:

rot_rect = canvas.get_rect(center = pos)
surface.blit(canvas, rot_rect)    

Minimal example:

from pygame import * 
import sys

def drawShip(pos, angle, image, surface):   
    rot_image = transform.rotate(image, angle)
    rot_rect = rot_image.get_rect(center = pos)
    surface.blit(rot_image, rot_rect)      

init()
s = display.set_mode((500,500))
clock = time.Clock()

image = Surface((100, 100), SRCALPHA)
image.fill((255, 0, 0))
angle = 0

while True:
    clock.tick(60)
    for e in event.get():
        if e.type == QUIT:
            sys.exit()
    if any(key.get_pressed()):
        angle += 1
    s.fill(0)
    drawShip((250,250), angle, image, s)
    display.flip()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174