Pygame Zero Collision Detection Not Working

78 views Asked by At

I am a beginner trying to make a game that gives me a point whenever the ball is on the target (a white line) and I press my mouse. For some reason, the game gives me a point when I click the mouse even when the ball is not on the line.

This is my code:

import pgzrun
import pygame
import sys

WIDTH = 800
HEIGHT = 800
score = 0
lives = 3

ball = Actor("redball")
ball.pos = 100,700

target = Actor("linetarget")
target.pos = 400,680

def draw():
    screen.clear()
    ball.draw()
    target.draw()
    

def update():
    ball.x += 10
    if ball.x == 800:
        ball.x = 100

def on_mouse_down():
    global score
    global lives
    if ball.colliderect(target):
        score += 1
        print(score)

    else:
        lives -= 1
        if lives == 0:
            sys.quit()

   


   


I am also accepting answers in Pygame. Please help!
1

There are 1 answers

2
BoppreH On

Your code works fine here, so a shot in the dark: you're using images with too much whitespace.

Note that when you create the actors you never specify their sizes, only positions:

ball = Actor("redball")
ball.pos = 100,700

target = Actor("linetarget")
target.pos = 400,680

The size is taken from the underlying image. If your redball.png or linetarget.png have too many empty pixels (transparent or not!), then colliderect will report collisions when the ball/line themselves are not touching.

My suggestion: open your images in an image editor (mspaint would do) and make sure the canvas fits the ball/line snuggly without empty borders around. You'll have to resize the image, not just select and delete white pixels.

And even in the best of cases, your collision will not be perfect for another reason: colliderect checks for axis-aligned-bounding boxes. That means your redball will always have empty spots around it (the rectangle corners), and your linetarget too if it's not perfectly vertical/horizontal (with 45 degrees being the worst case).