简体   繁体   中英

pygame sprite collision on left

I want to do special collisions with pygame. I have a Ball sprite and a Block sprite and I want to know on which side of the block the ball has collided.

Maybe it's possible with pygame.sprite.groupcollide() and a custom collided as they call it. But I found no answser for that question. Is there any way to do it ?

Yes, it is possible. You are correct about the collided argument too.

What you need to do is write a function that will take 2 sprites and return a boolean value.

In this function you can then check on which side they have collided, and inform the sprites of the collision, or even return true only when a certain type of collision has happened.

Since every sprite has a rect attribute, you can check there way of movement as well as their positions to see where they have collided.

For example, if we have two sprites, A,B one going up and the other going left, they can collide in two ways. You can test if A has collided from the top, if after the collision, the second sprite is higher than A.

Heres a link to the pygame documentation I found:

pygame documentation

If your using a browser with a search page function search for:

pygame.sprite.spritecollide()

Im not too good with pygame, but understand the basics. I think the correct function is

pygame.sprite.collide_mask()

Which as the docs say:

"Returns first point on the mask where the masks collided, or None if there was no collision.

Tests for collision between two sprites, by testing if thier bitmasks overlap. If the sprites have a “mask” attribute, that is used as the mask, otherwise a mask is created from the sprite image. Intended to be passed as a collided callback function to the *collide functions. Sprites must have a “rect” and an optional “mask” attribute.

You should consider creating a mask for your sprite at load time if you are going to check collisions many times. This will increase the performance, otherwise this can be an expensive function because it will create the masks each time you check for collisions."

Hope it helped.

-Harry

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM