简体   繁体   中英

Is there a way to get the co-ordinates of the point of collision?

I am making a game in which the change in velocity of a ball depends on the point at which it collides with an object. I looked up the documentation but was unable to find something to do the job.

Is there any way to get the coordinates of the point of collision in Pygame?

Yes, work out the difference in the x and y co-ordinates of your ball and object. Then use mask.overlap from pygame to return a tuple of the point of collision. An example would be:

def collide(obj1, obj2):
    offset_x = obj2.x - obj1.x
    offset_y = obj2.y - obj1.y
    return obj1.mask.overlap(obj2.mask, (offset_x, offset_y))

You can find the docs for 'mask.overlap()' here .

I support the answer given by Abishake Srithar. This is not meant to displace that answer, just add information to it.

A slight caution about the result of this mask.overlap() call. It does not give you the center of where the point of contact might be.

As you can see in the description in the docs here , the overlap is searched for by proceeding top to bottom in columns moving left to right. Which means that overlap() returns the leftmost, upper (sort of) point of the overlap.

So if your update/move of the objects causes the objects to overlap over an area (which is likely), the point returned by overlap() is the leftmost, upper point of that overlap. It is not the center of the area, or the point where the two objects might have first touched if they were not overlapping.

An example is if this were two spheres colliding, it will give you the edge of the overlap and not actually the centerpoint of the collision. This could change your angles of reflection.

This difference can affect the collision physics.

It is likely good enough for most games but I thought it worth pointing out.

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