[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Collision detection help - colliderect



There are several problems with your code, and I've altered the
pastebin to identify them.

I *strongly* encourage you to read the Chimp Line-By-Line tutorial and
perhaps also a Python tutorial as well, but I'll try to answer your
specific question.

The function in question is check_hit:

> def check_hit():
>   for i in bullets:
>     if b.rect.colliderect(B.rect):
>       channel = boom_snd.play()

A for loop iterates through a collection of items.

for i in bullets:
  print i
  print i.image

See how i is a bullet?  You don't need to hack around trying to create
a global 'b' object.

So your for loop could look like:
for bullet in bullets:
  for barney in barneys:
    if bullet.colliderect(barney.rect):
      # do stuff

Now your second fundamental problem: your object's .rect attributes
are never updated.  The way you wrote it, you're never using .rect at
all because all your objects have their own .x and .y attributes.  You
should switch over to actually *using* the .rect attributes and get
rid of the .x and .y attributes.

How about this for starters?

class Bullet(...):
  def __init__(self, name, x, y):
    self.image = ...
    self.rect = self.image.get_rect()
    self.rect.x = x
    self.rect.y = y

That should get you over the hump, but seriously, read and understand
the Chimp tutorial.  You'll probably learn faster by asking the list
about the parts of the Chimp tutorial that you don't understand than
by asking about your code that we have to read and figure out what
your intent was.

Keep it up!

sjbrown


On Fri, Nov 7, 2008 at 1:18 PM, IamScuzzo <i.am.scuzzo@xxxxxxxxx> wrote:
> I am trying to check a collision between "b" and "B". "b" is the
> bullet sprite from the Bullet class, and B is the barney sprite from
> the Barney class.
>
> Link: http://pastebin.com/m4d7304fc
>
> Right now nothing happens when I run the game, no collision detections
> and no error messages. I cant figure out what I am doing wrong. It was
> complaining about how b isnt defined so I made it global, same with B.
>