Finding the center of an image to define a hitbox - python

I'm trying to select the center of my image to make a hitbox some pixels around it.
I was able to inflate() the hitbox to make it the right size, but it always uses the top left corner of the image. This is fine when i'm moving left, but when i turn right it goes away from the character (in the image the character is dragging a sword, so it goes way off center).
I've been reading about Vector2, pos and offset, but i can't get it to work.
In conclusion i need to learn a way to find the center of my image in order to place it's hitbox a few pixels to each side. Either that or how to "shift" the corner the hitbox uses so it's always in the front of the char.

Use a pygame.Rect object. Get the rectangle from the pygame.Surface object (image) and set the top left corner position (x, y) of the rectangle. e.g.:
rect = image.get_rect()
rect.topleft = (x, y)
respectively
rect = image.get_rect(topleft = (x, y))
pygame.Rect provides a lot of virtual attributes, which can be used to retrieve the corners, borders, center and size of the rectangle. .center returns the center of the rectangle:
center_x, center_y = rect.center

Related

How to center an image in the middle of the window in pygame?

So I am Loading an Image in python and I need to Center the Image in Pygame. As Pygame starts the drawing from the upper left side of the screen so the x and y coordinates 0,0 doesn't work. Can anyone tell me the center x and y coordinates of the pygame window?
You can get the center of the window through the window rectangle (pygame.Surface.get_rect):
screen = pygame.display.set_mode((800, 600))
center = screen.get_rect().center
Use this to blit an image (pygame.Surface object) in the center of the screen:
screen.blit(image, image.get_rect(center = screen.get_rect().center))
pygame.Surface.get_rect() returns a rectangle with the size of the Surface object, that always starts at (0, 0). However, the position of the rectangle can be specified with a keyword argument. In this case, the center of the rectangle is set by the center of the screen.
When the 2nd argument of blit is a rectangle (pygame.Rect), the upper left corner of the rectangle will be used as the position for the blit.

Rotating the player about the center point in pygame

I am making a game where there are two players and they can shoot each other. Their movement will be defined by a rotation around a fixed point, the point will be(600, 300), which is the center of our screen. The player will keep rotating around the point as long as they are pressing a certain button(which is keep providing force to our player) else they will fall(due to gravity). I think it would help to think of it as a ball attached to a point using a string. The string is attached as long as a button is pressed and gets unattached as soon as the button is released and the ball flies off. Here is my player class
class Player:
def __init__(self):
self.pos = [500, 200]
self.width = 30
self.height = 30
self.player = pygame.image.load("player.png").convert_alpha()
self.player = pygame.transform.scale(self.player, (self.width, self.height))
self.rect = self.player.get_rect()
self.rotated_player = None
self.anguler_vel = 0
self.Fg = 0.05
self.Fp = 0
self.arm_length = 0
Fp is the force perpendicular to the force of gravityFg. Fg is the force which is pulling it down on our player. Fp is defined by math.sin(theta) * Fg. I am keeping track of Fp because i want the player to keep moving in the direction of rotation after its unattatched from the string. arm_length is the length of the string.
I have a Point class, which is the point about which our player will rotate. Here's the point class.
class Point:
def __init__(self,x, y):
self.pos = [x, y]
dx = self.pos[0] - player.pos[0]
dy = self.pos[1] - player.pos[1]
self.angle = math.atan2(dy, dx)
Now, i need help with the actual rotation itself. I am aware that adding a certain value to the angle every single frame would make it go around. But how would i make it go around a certain point that i specify and how would the arm length tie into this?. I find that it is really difficult to implement all of this because the y-axis is flipped and all the positional values have to be scaled down when using them in calculations because of the FPS rate. Any help on how this is done would be appreciated as well. Thanks
When you use pygame.transform.rotate the size of the new rotated image is increased compared to the size of the original image. You must make sure that the rotated image is placed so that its center remains in the center of the non-rotated image. To do this, get the rectangle of the original image and set the position. Get the rectangle of the rotated image and set the center position through the center of the original rectangle. e.g.:
def rotate_center(image, rect, angle):
rotated_image = pygame.transform.rotate(image, angle)
new_rect = rotated_image.get_rect(center = rect.center)
return rotated_image, new_rect
screen.blit(*rotate_center(image, image_rect, angle))
Alos see How do I rotate an image around its center using PyGame? and How to rotate an image(player) to the mouse direction?

Pygame: What is the Rect() arguments exactly, and what do they represent?

Here is what I understand so far about Rect, it is a data type that contains all the properties of a given rectangular surface. And is used along the pygame.draw.rect() function as the third argument in order for it to work.
The code follows this syntax (from the official documentation):
Rect(left, top, width, height)
I understand about the third and fourth argument, which suppose to represent the dimensions of the rectangular surface. What I don't understand is the first 2 argument - what is it suppose to represent and what does it do? Why does it always start at (0,0) and what can we use it for?
The first two arguments get assigned to the x and y attributes of the rect, the coordinates of the topleft corner. So if you want to create a rect that is positioned at the coordinates (200, 300), you can write: rect = pygame.Rect(200, 300, 40, 50). The third and fourth argument are indeed the dimensions of the resulting rect instance.
pygame.Rects also have a lot of other attributes which you can use to position your rect.
x,y
top, left, bottom, right
topleft, bottomleft, topright, bottomright
midtop, midleft, midbottom, midright
center, centerx, centery
If you want to move a rect, you can assign the new position to the x, y, topleft or one of the other attributes.
rect.x = 5
rect.y = 10
# That's pretty much the same as writing:
rect.topleft = (5, 10)
# You can also increment the position.
rect.x += 5
# Or use the `rect.move_ip` method.
rect.move_ip(5, 10)
Rects are used to store the blit position of sprites or images and for collision detection, for example with the colliderect or collidepoint methods.

Pygame - What happens if you blit a surface with a rect smaller than the surface?

In this blit call
screen = pygame.Surface(640, 480)
bgsurf = pygame.Surface(640, 480)
new_rect = pygame.Rect(0, 0, 80, 80)
screen.blit(bgsurf, new_rect, new_rect)
how pygame decides which portion of bgsurf it will copy to the screen in the new_rect area?
From the pygame docs:
blit(source, dest, area=None, special_flags = 0) -> Rect
Draws a source Surface onto this Surface. The draw can be positioned
with the dest argument. Dest can either be pair of coordinates
representing the upper left corner of the source. A Rect can also be
passed as the destination and the topleft corner of the rectangle will
be used as the position for the blit. The size of the destination
rectangle does not effect the blit.
An optional area rectangle can be passed as well. This represents a
smaller portion of the source Surface to draw.
So as you can see, pygame would blit the whole surface at (0,0).
If you want to blit a part of surface, you need to pass in the area Rect.
EDIT:
In your case, it will blit the subsurface given by new_rect onto screen where the top-left corner will be placed at (0,0).

Weird shifting when using pygame.transform.rotate()

def rotate(self):
#Save the original rect center
self.saved_center=self.rect.center
#Rotates a saved image every time to maintain quality
self.image=pygame.transform.rotate(self.saved_image, self.angle)
#Make new rect center the old one
self.rect.center=self.saved_center
self.angle+=10
When I rotate the image, there is a weird shifting of it despite the fact that I'm saving the old rect center and making the rotated rect center the old one. I want it to rotate right at the center of the square.
Here's what it looks like:
http://i.imgur.com/g6Os9.gif
You are just calculating the new rect wrong. Try this:
def rotate(self):
self.image=pygame.transform.rotate(self.saved_image, self.angle)
self.rect = self.image.get_rect(center=self.rect.center)
self.angle+=10
It tells the new rect to center itself around the original center (the center never changes here. Just keeps getting passed along).
The issue was that the self.rect was never being properly updated. You were only changing the center value. The entire rect changes as the image rotates because it grows and shrinks in size. So what you needed to do was completely set the new rect each time.
self.image.get_rect(center=self.rect.center)
This calculates a brand new rect, while basing it around the given center. The center is set on the rect before it calculate the positions. Thus, you get a rect that is properly centered around your point.
I had this issue. My method has a bit of a different purpose, but I solved it quite nicely.
import pygame, math
def draw_sprite(self, sprite, x, y, rot):
#'sprite' is the loaded image file.
#'x' and 'y' are coordinates.
#'rot' is rotation in radians.
#Creates a new 'rotated_sprite' that is a rotated variant of 'sprite'
#Also performs a radian-to-degrees conversion on 'rot'.
rotated_sprite = pygame.transform.rotate(sprite, math.degrees(rot))
#Creates a new 'rect' based on 'rotated_sprite'
rect = rotated_sprite.get_rect()
#Blits the rotated_sprite onto the screen with an offset from 'rect'
self.screen.blit(rotated_sprite, (x-(rect.width/2), y-(rect.height/2)))

Categories

Resources