why is my collision test always returning 'true' and why is the position of the rectangle of the image always wrong (0, 0)?

  • Last Update :
  • Techknowledgy :

You've to set the location of the rectangle, either by a keyword argument, e.g:

self.rect = self.image.get_rect(topleft = (self.x, self.y))

or an assignment to a virtual attribute (see pygame.Rect), e.g:

self.rect = self.image.get_rect()
self.rect.topleft = (self.x, self.y)

It is absolutely unnecessary to add some extra attributes self.x and self.y. Use the location of the rectangle instead. e.g:

class Ball(pygame.sprite.Sprite):
   def __init__(self):
   pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("ball.png")
self.rect = self.image.get_rect(topleft = (280, 475))
self.col = False
def update(self):
   gameDisplay.blit(self.image, self.rect)
def test_collisions(self, sprite):
   self.col = pygame.sprite.collide_rect(self, sprite)

class Obstacle(pygame.sprite.Sprite):
   def __init__(self):
   pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("obstacle.png")
self.time = pygame.time.get_ticks()
self.rect = self.image.get_rect(topleft = (1000, 483))
def change_x(self):
   self.time = pygame.time.get_ticks()
self.rect.x = -(self.time / 5) + 800
def update(self):
   gameDisplay.blit(self.image, self.rect)

Suggestion : 2

You've to set the location of the anycodings_pygame-surface rectangle, either by a keyword argument, anycodings_pygame-surface e.g:,How do I fit an image (img) inside a div and keep the aspect ratio?,It is absolutely unnecessary to add some anycodings_pygame-surface extra attributes self.x and self.y. Use anycodings_pygame-surface the location of the rectangle instead. anycodings_pygame-surface e.g:,pygame.Surface.get_rect.get_rect() anycodings_pygame-surface returns a rectangle with the size of the anycodings_pygame-surface Surface object, but it returns a anycodings_pygame-surface rectangle that always starts at (0, 0) anycodings_pygame-surface since a Surface object has no anycodings_pygame-surface position. The Surface is placed at a anycodings_pygame-surface position on the display with the blit anycodings_pygame-surface function.

My collide_rect function isn't working anycodings_pygame-surface properly. It always returns True, when it's anycodings_pygame-surface not suppose to. I have tried looking on the anycodings_pygame-surface internet but nothing is working for me. I anycodings_pygame-surface think the collide rect somehow did not use anycodings_pygame-surface the actual coordinates for the two sprites. anycodings_pygame-surface Can anyone help with this?

import pygame
import pygame.sprite
import sys

gameDisplay = pygame.display.set_mode((800, 600))
pygame.display.set_caption("test_collision")
clock = pygame.time.Clock()
crashed = False

class Ball(pygame.sprite.Sprite):
   def __init__(self):
   pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("ball.png")
self.rect = self.image.get_rect()
self.x = 280
self.y = 475
self.col = False
def update(self):
   gameDisplay.blit(self.image, (self.x, self.y))
self.rect = self.image.get_rect()
def test_collisions(self, sprite):
   self.col = pygame.sprite.collide_rect(self, sprite)
class Obstacle(pygame.sprite.Sprite):
   def __init__(self):
   pygame.sprite.Sprite.__init__(self)
self.x = 1000
self.y = 483
self.image = pygame.image.load("obstacle.png")
self.time = pygame.time.get_ticks()
self.rect = self.image.get_rect()
def change_x(self):
   self.time = pygame.time.get_ticks()
self.x = -(self.time / 5) + 800
def update(self):
   self.rect = self.image.get_rect()
gameDisplay.blit(self.image, (self.x, self.y))

obstacle = Obstacle()
ball = Ball()
while not crashed:
   for event in pygame.event.get():
   if event.type == pygame.QUIT:
   crashed = True
gameDisplay.fill((255, 255, 255))
ball.update()
obstacle.change_x()
obstacle.update()
ball.test_collisions(obstacle)
if ball.col:
   print("colided")
pygame.display.flip()
clock.tick(1000)

pygame.quit()
sys.exit()

You've to set the location of the anycodings_pygame-surface rectangle, either by a keyword argument, anycodings_pygame-surface e.g:

self.rect = self.image.get_rect(topleft = (self.x, self.y))

or an assignment to a virtual attribute anycodings_pygame-surface (see pygame.Rect), e.g:

self.rect = self.image.get_rect()
self.rect.topleft = (self.x, self.y)

It is absolutely unnecessary to add some anycodings_pygame-surface extra attributes self.x and self.y. Use anycodings_pygame-surface the location of the rectangle instead. anycodings_pygame-surface e.g:

class Ball(pygame.sprite.Sprite):
   def __init__(self):
   pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("ball.png")
self.rect = self.image.get_rect(topleft = (280, 475))
self.col = False
def update(self):
   gameDisplay.blit(self.image, self.rect)
def test_collisions(self, sprite):
   self.col = pygame.sprite.collide_rect(self, sprite)

class Obstacle(pygame.sprite.Sprite):
   def __init__(self):
   pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("obstacle.png")
self.time = pygame.time.get_ticks()
self.rect = self.image.get_rect(topleft = (1000, 483))
def change_x(self):
   self.time = pygame.time.get_ticks()
self.rect.x = -(self.time / 5) + 800
def update(self):
   gameDisplay.blit(self.image, self.rect)

Suggestion : 3

In PyGame, basic collision detection can be done using pygame.Rect objects. The Rect object offers various methods for detecting collisions between objects. Note that even the collision of a rectangular object with a circular object such as a paddle and a ball in Pong game can be roughly detected by a collision between two rectangular objects, the paddle and the bounding rectangle of the ball.,How to detect collisions between two rectangular objects or images in pygame Why is my collision test always returning 'true' and why is the position of the rectangle of the image always wrong (0, 0)?, How to detect collisions between two rectangular objects or images in pygame Why is my collision test always returning 'true' and why is the position of the rectangle of the image always wrong (0, 0)? ,How to detect collisions between two rectangular objects or images in pygame

import pygame

pygame.init()
window = pygame.display.set_mode((250, 250))
rect = pygame.Rect( * window.get_rect().center, 0, 0).inflate(100, 100)

run = True
while run:
   for event in pygame.event.get():
   if event.type == pygame.QUIT:
   run = False

point = pygame.mouse.get_pos()
collide = rect.collidepoint(point)
color = (255, 0, 0) if collide
else(255, 255, 255)

window.fill(0)
pygame.draw.rect(window, color, rect)
pygame.display.flip()

pygame.quit()
exit()
import pygame

pygame.init()
window = pygame.display.set_mode((250, 250))
rect1 = pygame.Rect( * window.get_rect().center, 0, 0).inflate(75, 75)
rect2 = pygame.Rect(0, 0, 75, 75)

run = True
while run:
   for event in pygame.event.get():
   if event.type == pygame.QUIT:
   run = False

rect2.center = pygame.mouse.get_pos()
collide = rect1.colliderect(rect2)
color = (255, 0, 0) if collide
else(255, 255, 255)

window.fill(0)
pygame.draw.rect(window, color, rect1)
pygame.draw.rect(window, (0, 255, 0), rect2, 6, 1)
pygame.display.flip()

pygame.quit()
exit()
import pygame

pygame.init()
window = pygame.display.set_mode((250, 250))

sprite1 = pygame.sprite.Sprite()
sprite1.image = pygame.Surface((75, 75))
sprite1.image.fill((255, 0, 0))
sprite1.rect = pygame.Rect( * window.get_rect().center, 0, 0).inflate(75, 75)
sprite2 = pygame.sprite.Sprite()
sprite2.image = pygame.Surface((75, 75))
sprite2.image.fill((0, 255, 0))
sprite2.rect = pygame.Rect( * window.get_rect().center, 0, 0).inflate(75, 75)

all_group = pygame.sprite.Group([sprite2, sprite1])
test_group = pygame.sprite.Group(sprite2)

run = True
while run:
   for event in pygame.event.get():
   if event.type == pygame.QUIT:
   run = False

sprite1.rect.center = pygame.mouse.get_pos()
collide = pygame.sprite.spritecollide(sprite1, test_group, False)

window.fill(0)
all_group.draw(window)
for s in collide:
   pygame.draw.rect(window, (255, 255, 255), s.rect, 5, 1)
pygame.display.flip()

pygame.quit()
exit()
import pygame

pygame.init()
window = pygame.display.set_mode((250, 250))

sprite1 = pygame.sprite.Sprite()
sprite1.image = pygame.Surface((80, 80), pygame.SRCALPHA)
pygame.draw.circle(sprite1.image, (255, 0, 0), (40, 40), 40)
sprite1.rect = pygame.Rect( * window.get_rect().center, 0, 0).inflate(40, 40)
sprite2 = pygame.sprite.Sprite()
sprite2.image = pygame.Surface((80, 89), pygame.SRCALPHA)
pygame.draw.circle(sprite2.image, (0, 255, 0), (40, 40), 40)
sprite2.rect = pygame.Rect( * window.get_rect().center, 0, 0).inflate(80, 80)

all_group = pygame.sprite.Group([sprite2, sprite1])
test_group = pygame.sprite.Group(sprite2)

run = True
while run:
   for event in pygame.event.get():
   if event.type == pygame.QUIT:
   run = False

sprite1.rect.center = pygame.mouse.get_pos()
collide = pygame.sprite.spritecollide(sprite1, test_group, False, pygame.sprite.collide_circle)

window.fill(0)
all_group.draw(window)
for s in collide:
   pygame.draw.circle(window, (255, 255, 255), s.rect.center, s.rect.width // 2, 5)
      pygame.display.flip()

      pygame.quit() exit()
while run:
   #[...]

key = pygame.key.get_pressed()
if key[pygame.K_w]:
   paddle1.rect.y += -paddle_speed

#[...]

winRect = win.get_rect()
paddle1.rect.clamp_ip(winRect)
paddle2.rect.clamp_ip(winRect)
paddle3.rect.clamp_ip(winRect)
paddle4.rect.clamp_ip(winRect)

#[...]
import math

Suggestion : 4

Here’s an example that shows a center rectangle and a rectangle at the mouse position. If the two rectangles are colliding, the mouse rectangle turns red:,This is just the code version of what we already talked about with the 4 rectangles that do not collide with our main rectangle.,Let’s say we were going to create an anti-collision-detection algorithm that evaluates to true when two rectangles are not colliding. We would put the above cases into code that looks like this:,This code uses the above technique to detect when the mouse is inside the rectangle, and change its color to red.

float x = 150;
float y = 100;
float xSpeed = 5;
float ySpeed = 4;

void setup() {
   size(300, 300);
}

void draw() {
   background(64);
   ellipse(x, y, 25, 25);

   x += xSpeed;
   y += ySpeed;

   if (x < 0 || x > width) {
      xSpeed *= -1;
   }

   if (y < 0 || y > height) {
      ySpeed *= -1;
   }
}
float circleCenterX;
float circleCenterY;
float circleRadius;

void setup() {
   size(300, 300);
   circleCenterX = width / 2;
   circleCenterY = height / 2;
   circleRadius = 100;
}

void draw() {
   background(0);

   if (dist(mouseX, mouseY, circleCenterX, circleCenterY) < circleRadius) {
      fill(255, 0, 0);
   } else {
      fill(0, 255, 0);
   }

   ellipse(circleCenterX, circleCenterY, circleRadius * 2, circleRadius * 2);
}
float bigCircleRadius = 50;
float smallCircleRadius = 25;

void setup() {
   size(300, 300);
}

void draw() {
   background(64);

   //draw the big circle
   noFill();
   stroke(255);
   ellipse(width / 2, height / 2, bigCircleRadius * 2, bigCircleRadius * 2);

   //change color if circles are colliding
   if (dist(mouseX, mouseY, width / 2, height / 2) < bigCircleRadius + smallCircleRadius) {
      fill(255, 0, 0);
   } else {
      fill(0, 255, 0);
   }

   //draw the small circle
   ellipse(mouseX, mouseY, smallCircleRadius * 2, smallCircleRadius * 2);

}
if (dist(mouseX, mouseY, width / 2, height / 2) < bigCircleRadius + smallCircleRadius) {
if (pointX > rectX && pointX < rectX + rectWidth) {
if (pointY > rectY && pointY < rectY + rectHeight) {

Suggestion : 5

Last Updated : 06 Aug, 2022

Rectangles Overlap

Suggestion : 6

Selecting data from an array by boolean indexing always creates a copy of the data, even if the returned array is unchanged.,Suppose each name corresponds to a row in the data array and we wanted to select all the rows with corresponding name 'Bob'. Like arithmetic operations, comparisons (such as ==) with arrays are also vectorized. Thus, comparing names with the string 'Bob' yields a boolean array:,The numpy.where function is a vectorized version of the ternary expression x if condition else y. Suppose we had a boolean array and two arrays of values:,The boolean array must be of the same length as the axis it’s indexing. You can even mix and match boolean arrays with slices or integers (or sequences of integers, more on this later):

In[13]: data1 = [6, 7.5, 8, 0, 1]

In[14]: arr1 = np.array(data1)

In[15]: arr1
Out[15]: array([6., 7.5, 8., 0., 1.])
In[27]: arr1 = np.array([1, 2, 3], dtype = np.float64)

In[28]: arr2 = np.array([1, 2, 3], dtype = np.int32)

In[29]: arr1.dtype In[30]: arr2.dtype
Out[29]: dtype('float64') Out[30]: dtype('int32')
In[45]: arr = np.array([
   [1., 2., 3.],
   [4., 5., 6.]
])

In[46]: arr
Out[46]:
   array([
      [1., 2., 3.],
      [4., 5., 6.]
   ])

In[47]: arr * arr In[48]: arr - arr
Out[47]: Out[48]:
   array([
      [1., 4., 9.], array([
         [0., 0., 0.],
         [16., 25., 36.]
      ])[0., 0., 0.]
   ])
In[51]: arr = np.arange(10)

In[52]: arr
Out[52]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In[53]: arr[5]
Out[53]: 5

In[54]: arr[5: 8]
Out[54]: array([5, 6, 7])

In[55]: arr[5: 8] = 12

In[56]: arr
Out[56]: array([0, 1, 2, 3, 4, 12, 12, 12, 8, 9])
In[75]: arr[1: 6]
Out[75]: array([1, 2, 3, 4, 64])
In[83]: names = np.array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe'])

In[84]: data = np.random.randn(7, 4)

In[85]: names
Out[85]:
   array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe'],
      dtype = '|S4')

In[86]: data
Out[86]:
   array([
      [-0.048, 0.5433, -0.2349, 1.2792],
      [-0.268, 0.5465, 0.0939, -2.0445],
      [-0.047, -2.026, 0.7719, 0.3103],
      [2.1452, 0.8799, -0.0523, 0.0672],
      [-1.0023, -0.1698, 1.1503, 1.7289],
      [0.1913, 0.4544, 0.4519, 0.5535],
      [0.5994, 0.8174, -0.9297, -1.2564]
   ])