pygame.transform.rotate() acting weird [duplicate] - python

This question already has answers here:
How do I rotate an image around its center using Pygame?
(6 answers)
Closed 2 years ago.
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

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()

Related

I would like to describe a parabola when a battle ship shoot a bullet with pygame [duplicate]

This question already has answers here:
How do I rotate an image around its center using Pygame?
(6 answers)
Closed 2 years ago.
I'm trying to animate a ball getting thrown, and I want it to rotate an follow a smooth, parabolic path at the same time. However, I just can't seem to get pygame.transform.rotate() to cooperate.
Here's what I've tried so far:
import pygame
screen = pygame.display.set_mode((500, 500))
timer = pygame.time.Clock()
ball = pygame.sprite.Sprite()
ball.image = pygame.image.load("throwball.png")
ball.image = pygame.transform.scale(ball.image, (48,48))
ball.rect = ball.image.get_rect(topleft = (50,50))
ball.orig_image = ball.image
rotaterect = ball.rect
for i in range(60):
#pygame.draw.rect(screen, Color(255,255,255), ball.rect)
ball.image = pygame.transform.rotate(ball.orig_image, i*20)
rotaterect.topleft = (5*i,((i-20)*(i-20) + 1)/5)
ball.rect.center = rotaterect.center
screen.blit(ball.image, ball.rect)
pygame.display.update()
timer.tick(60)
for e in pygame.event.get():
if e.type == pygame.QUIT:
pygame.quit()
sys.exit()
while 1:
for e in pygame.event.get():
if e.type == pygame.QUIT:
pygame.quit()
sys.exit()
Whenever I run the code, the ball moves in an irregular pattern. I made a second rect to try to keep the positioning under control, but the ball ends up forming a path like this:
Obviously there's something wrong with the positioning on each frame, but I'm not sure why any of the frames would be out of place, since their location is determined by their center point.
Here's the ball image:
It's 16x16 (square), so I'm dumbfounded as to why the image isn't following a clean path.
Note, a rotated image varies in size. See How do I rotate an image around its center using Pygame?.
Get the rectangle of the rotated image and set the center of the rectangle by the center of the helper rectangle rotaterect. This causes that the image is symmetrically aligned around the center.
You missed to update the ball.rect to the actual size of the rotated image:
ball.rect = ball.image.get_rect()
rotaterect.topleft = (5*i,((i-20)*(i-20) + 1)/5)
ball.rect.center = rotaterect.center
Example:
for i in range(60):
ball.image = pygame.transform.rotate(ball.orig_image, i*20)
ball.rect = ball.image.get_rect()
rotaterect.topleft = (5*i,((i-20)*(i-20) + 1)/5)
ball.rect.center = rotaterect.center
screen.blit(ball.image, ball.rect)
pygame.display.update()

how to center text in a rectangle in pygame [duplicate]

This question already has answers here:
How to Center Text in Pygame
(6 answers)
Closed 1 year ago.
im making a game in pygame and I can't figure out how I can center some text in a rectangle. I draw the rectangle by using pygame.draw_rect(win, color, (x, y, w, h)) and text with
text = font.render("text", 1, color).
i know I can use text_rect = text.get_Rect(), to get a rect object of the text. but I don't know how to use those to center the text. I was searching for a solution online and couldn't find it
You can get a rect from the surface generated by rendering your font. Then set the centre that rect to the centre of your rectangle. Then blit your font surface to the main surface.
Here's a small example that uses the mousewheel to enlarge and shrink the border rectangle to show that the font remains centred. Pressing a key randomises the text.
import random
import pygame
WIDTH, HEIGHT = 320, 240
pygame.init()
pygame.font.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
# use the first available font
font = pygame.font.SysFont(pygame.font.get_fonts()[0], 60)
pygame.display.set_caption("Centering Font Rect")
text = "Initial Text"
widget = font.render(text, True, pygame.Color("seagreen"))
border = pygame.Rect(10, 10, WIDTH - 40, HEIGHT - 40)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
# change the text
text = random.choice(["Short", "Long Looooong", ".", "+++", "ABC"])
widget = font.render(text, True, pygame.Color("purple"))
elif event.type == pygame.MOUSEWHEEL:
# enlarge or shrink the border rect
border.inflate_ip(event.y, event.y)
screen.fill(pygame.Color("turquoise"))
# draw border rect
pygame.draw.rect(screen, pygame.Color("red"), border, width=1)
# get the current font rect
font_rect = widget.get_rect()
# move rect to be centered on border rect
font_rect.center = border.center
screen.blit(widget, font_rect)
# update display
pygame.display.update()
pygame.quit()
This shows:
Then after some resizing:

Pygame mouse event.rel not working outside window [duplicate]

This question already has answers here:
pygame capture keyboard events when window not in focus
(2 answers)
Get Inputs without Focus in Python/Pygame?
(3 answers)
Closed 3 months ago.
I'm trying to implement a feature in Pygame where if the user moves the mouse outside the window the relative position (event.rel) can be returned. I'm trying to do this because I want to make a game where you can keep turning left or right from mouse input.
I know this is possible from the docs:
If the mouse cursor is hidden, and input is grabbed to the current display the mouse will enter a virtual input mode, where the relative movements of the mouse will never be stopped by the borders of the screen. See the functions pygame.mouse.set_visible() and pygame.event.set_grab() to get this configured.
For this reason, I've implemented these lines in my code
pygame.mouse.set_visible(False)
pygame.event.set_grab(True)
However this doesn't help. The actual behaviour is:
when the mouse is moving in the window, event.rel prints to the console (expected)
when the mouse is moving outside the window, event.rel doesn't print to the console (not expected)
Other strange behaviour:
Initially event.rel is set to (300, 300) which is the center of my 600x600 screen. Ideally initial event.rel should be (0,0)
Possible cause:
I'm running the code below in trinket.io or repl.it. Because this is a browser the demo window might cause problems. Maybe this is solved by downloading python locally but i don't want to do this as it takes up too much space (my laptop sucks) and also it would be good to have an online demo to easily show employers that are too lazy to paste code into their IDEs.
Similar issue:
This guy on reddit had a very similar issue but I think his solution is not related to my situation
This block of code was what I asked originally but it doesn't demonstrate the question as well as the last block. Please scroll down to see the last block of code instead :)
import pygame
pygame.init()
# screen
X = 600 # width
Y = 600 # height
halfX = X/2
halfY = Y/2
screen = pygame.display.set_mode((X, Y), pygame.FULLSCREEN)
clock = pygame.time.Clock()
# Colors
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# From the docs:
# "If the mouse cursor is hidden, and input is grabbed to the
# current display the mouse will enter a virtual input mode, where
# the relative movements of the mouse will never be stopped by the
# borders of the screen."
pygame.mouse.set_visible(False)
pygame.event.set_grab(True)
def drawCross(point, size, color):
pygame.draw.line(screen, color, (point[0]-size,point[1]-size), (point[0]+size,point[1]+size), 2)
pygame.draw.line(screen, color, (point[0]+size,point[1]-size), (point[0]-size,point[1]+size), 2)
canvas_rel = (halfX,halfY)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.MOUSEMOTION:
print('event.rel = ' + str(event.rel))
canvas_rel = [10 * event.rel[0] + halfX, 10 * event.rel[1] + halfY]
print(' canvas_rel = ' + str(canvas_rel))
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
print('escape')
running = False
break
screen.fill(WHITE)
# Red sight to represent pygame mouse event.rel
drawCross(canvas_rel, 10, RED)
pygame.display.flip()
clock.tick(20)
pygame.quit()
EDIT:
The above code doesn't fully demonstrate my problem. I've added a better sample below to make the the question easier to understand. This sample will draw a triangle in the centre of the screen. The triangle will rotate with relative horizontal motion of the mouse. Note the attempt to use pygame.mouse.set_pos
import pygame
from math import pi, cos, sin
pygame.init()
# screen
X = 600 # width
Y = 600 # height
halfX = X/2
halfY = Y/2
screen = pygame.display.set_mode((X, Y), pygame.FULLSCREEN)
clock = pygame.time.Clock()
# for getting relative mouse position when outside the screen
pygame.mouse.set_visible(False)
pygame.event.set_grab(True)
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
# sensitivity
senseTheta = 0.01
# player
stand = [halfX, halfY]
t = 0 # angle in radians from positive X axis to positive x axis anticlockwise about positive Z
# draws a white cross in the screen center for when shooting is implemented :)
def drawPlayer():
p = stand
d = 50
a1 = 0.25*pi-t
a2 = 0.75*pi-t
P = (p[0],p[1])
A1 = (p[0] + d*cos(a1), p[1] + d*sin(a1)) # P + (d*cos(a1), d*sin(a1))
A2 = (p[0] + d*cos(a2), p[1] + d*sin(a2)) # P + (d*cos(a2), d*sin(a2))
pygame.draw.line(screen, BLACK, P, A1, 2)
pygame.draw.line(screen, BLACK, A1, A2, 2)
pygame.draw.line(screen, BLACK, A2, P, 2)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.MOUSEMOTION:
mouseMove = event.rel
print('mouseMove = ' + str(mouseMove))
t -= mouseMove[0] * senseTheta
# "Fix" the mouse pointer at the center
# pygame.mouse.set_pos((screen.get_width()//2, screen.get_height()//2))
# But I think set_pos triggers another MOUSEMOTION event as moving in positive x
# seems to move backward the same amount in x (i.e. the triangle doesn't
# rotate). See the console log.
# If you uncomment this line it works ok (the triangle rotates) but still
# glitches when the mouse leaves the window.
# uncommented or not I still cant get the mouse to work outside the window
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
break
screen.fill(WHITE)
drawPlayer()
pygame.display.flip()
clock.tick(40)
pygame.quit()

How to centre an image in pygame? [duplicate]

This question already has an answer here:
How to center an image in the middle of the window in pygame?
(1 answer)
Closed 6 months ago.
I am using python 2.7, I would like to know if there is a way to centre an image in pygame. I have set the screen to fullscreen, is this possible? If it helps i will attach the code, thanks.
import pygame
import os
_image_library = {}
def get_image(path):
global _image_library
image = _image_library.get(path)
if image == None:
canonicalized_path = path.replace('/', os.sep).replace('\\', os.sep)
image = pygame.image.load(canonicalized_path)
_image_library[path] = image
return image
pygame.init()
screen = pygame.display.set_mode((0, 0))
done = False
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
screen.fill((0, 0, 0))
screen.blit(get_image('sw.png'), (0, 0)
pygame.display.flip()
clock.tick(60)
Yeah, it's possible.
You have to create a rect object of the image:
image = "insert image"
rect = image.get_rect ()
And then:
rect.center = ("coordinates of center")
This StackOverflow question might be able to help you.
Pygame Image position
Basically though, you'd get the image rectangle. From there there are a lot of useful functions you can call to position it.

Why am I getting this error: "Invalid rectstyle argument"

I am currently making a game in python where a ball hits a group of boxes. I have loaded an image of a grass that I wanted the boxes to stand on, the grass image is 600 by 151 pixels. So far I have all the boxes and the ball appearing perfectly however, What is not working currently is when I try to load the image and display it so that the boxes can stand on the grass image instead of falling off.
import pygame
from pygame.locals import *
from pygame.color import *
import pymunk as pm
from pymunk import Vec2d
import sys
from random import randint
def to_pygame(p):
"""Small hack to convert pymunk to pygame coordinates"""
return int(p[0]), int(-p[1]+600)
def add_box(space, size, pos, mass=1.0):
# pos is a Vec2d object
points = [(-size, -size), (-size, size), (size,size), (size, -size)]
moment = pm.moment_for_poly(int(mass), points, (0,0))
body = pm.Body(mass, moment)
body.position = pos
shape = pm.Poly(body, points, (0,0))
shape.friction = 1
space.add(body,shape)
return shape
def draw_box(screen, box):
ps = box.get_points()
ps.append(ps[0])
ps = map(to_pygame, ps)
pygame.draw.polygon(screen, THECOLORS["blue"], ps, 3)
def main():
pygame.init()
screen = pygame.display.set_mode((600, 600))
pygame.display.set_caption("Piling boxes")
clock = pygame.time.Clock()
boxes = []
x = 170
y = 120
space = pm.Space()
space.gravity = (0.0, -100.0)
### ground
body = pm.Body()
shape = pm.Segment(body, (150,100), (450,100), .0)
shape.friction = 4.4
space.add(shape)
for i in range(5):
# what is the mass of the box?
mass = randint(1,3)
# what size is the box?
size = randint(10, 35)
# calculate its position & hold it in a Vec2d
#x = x + size + 10
y = y + size
pos = Vec2d(x,y)
box = add_box(space, size, pos, mass)
boxes.append(box)
while 1:
clock.tick(15)
space.step(1/30.0)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit(0)
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit(0)
screen.fill(THECOLORS["white"])
test_image = pygame.image.load("grass.png")
screen.blit(test_image, to_pygame((450,100)), to_pygame((150,100)),3)
for i in range(len(boxes)):
draw_box(screen, boxes[i])
pygame.display.flip()
if __name__ == '__main__':
main()
No traceback or error log so it is a bit hard to identify the point of the error, an educated guess would be that you are passing Rectstyle arguments incorrectly somewhere. Please see the documentation for pygame.Rect on how to pass Rectstyle args correctly.
pygame.Rect(left, top, width, height): return Rect
pygame.Rect((left, top), (width, height)): return Rect
pygame.Rect(object): return Rect
The problem is
screen.blit(test_image, to_pygame((450,100)), to_pygame((150,100)),3)
To blit a surface to to screen, a valid blit is:
screen.blit(test_image, (450,100))
So you want:
screen.blit(test_image, to_pygame((450,100)))
Note: The extra args make me think maybe you're trying to use a source rect argument, to use a tileset. But in that case you wouldn't convert world to screen coords twice. Just on destination, not source.
If you do want the spritesheet/tileset, then out How do you select a sprite image from a sprite sheet in python? and Pygame.org/cookbook/SpriteSheet
The third argument in blit is the source area argument, should be a rectangle, not coordinates:
screen.blit(test_image, to_pygame((450,100)), to_pygame((150,100)),3)
Perhaps you want this:
screen.blit(test_image, to_pygame((450,100)), pygame.Rect((0,0), (150,100)), 3)
The problem is because your call to screen.blit is incorrect. See here.
The call could be
screen.blit(test_image, to_pygame((450,100)))
or perhaps if you wanted to use the area argument,
screen.blit(test_image, to_pygame((450,100)), pygame.Rect((0,0), (150,100)), 3)
Also, you are loading guess.png in every loop, instead move it out of the while loop, your code will perform better.

Categories