How to find the position of a Rect in python?

Question:

I was trying to make a code that moves a rect object (gotten with the get_rect function) but I need its coordinates to make it move 1 pixel away (if there are any other ways to do this, let me know.)

Here is the code:

import sys, pygame
pygame.init()
size = width, height = 1920, 1080
black = 0, 0, 0
screen = pygame.display.set_mode(size)
ball = pygame.image.load("ball.png")
rectball = ball.get_rect()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
rectball.move()
screen.fill(black)
screen.blit(ball, rectball)
pygame.display.flip()

You will notice that on line 11 the parameters are unfilled. This is because I was going to make it coords + 1.

Asked By: Kimo

||

Answers:

If I am correct I think it is rect.left or rect.top that gives it. Another method is to create another rectangle and check if the rectangle is in that.

Answered By: Riyan Nayak
#To move a rect object in Pygame, you can use the move_ip() method. This method takes two arguments, the x and y coordinates to move the rect by. For example, if you want to move the rect one pixel to the right and one pixel down, you can use the following code:

rectball.move_ip(1, 1)

#You can also use the x and y attributes of the rect to move it by a certain amount. For example, if you want to move the rect one pixel to the right, you can use the following code:

rectball.x += 1

#Note that this will only move the rect object and not the image that it represents. To move the image on the screen, you will also need to update the position of the ball surface using the blit() method.

#Here is an updated version of your code that moves the rect and the image on the screen:

import sys
import pygame

pygame.init()

size = width, height = 1920, 1080
black = 0, 0, 0

screen = pygame.display.set_mode(size)

ball = pygame.image.load("ball.png")
rectball = ball.get_rect()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    # Move the rect one pixel to the right and one pixel down
    rectball.move_ip(1, 1)

    # Update the position of the ball on the screen
    screen.blit(ball, rectball)

    pygame.display.flip()
Answered By: zeefxd
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.