0

I recently started coding in Pygame Zero before starting Pygame. I was making a game and the I need to see if two of the sprites are colliding. How should I approach this?

The two sprites: [1]: https://i.stack.imgur.com/bRcqC.png [2]: https://i.stack.imgur.com/FwlES.png

import pgzrun
import rando[enter image description here][1]m

WIDTH=400
HEIGHT=400
score=0

game_over=False

coin=Actor("coin")
fox=Actor("fox")

x=random.randint(0,WIDTH)

y=0

xf=170


fox.pos=(xf,150)
coin.pos=(x, 0 )

def draw():
  screen.fill((144,238,144))
  fox.draw()
  coin.draw()
  screen.draw.text("Score: "+str(score),(20,20),fontsize=30)

def relocate():
  global x
  global y
  y+=1
  coin.pos=(x, y )

def move():
    if keyboard.left :
        fox.x-=1
    if keyboard.right:
        fox.x+=1

def collide():
  global score
  global x
  global y

  if fox.rect.center==coin.rect.center:
    score+=1
    coin.pos=(x, 0 )



def update():
  global x
  global y
  relocate()
  if y>WIDTH-10:
    x=random.randint(0,WIDTH)
    y=0
    coin.pos=(x, y )
  move()
  collide()


pgzrun.go()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174

1 Answers1

0

To tell if two sprites collide, use the colliderect() method. Change the line:

  if fox.rect.center==coin.rect.center:

to

  if fox.colliderect(coin):

Actors have all the same attributes and methods as Rect, including methods like .colliderect() which can be used to test whether two actors have collided. – Pygame Zero Builtins

Nathan Mills
  • 2,243
  • 2
  • 9
  • 15