Pygame: Collision by Sides of Sprite

前端 未结 4 1414
春和景丽
春和景丽 2020-11-30 12:07

Is there a way in pygame to look for a collision between the a particular side of a sprite and a particular side of another sprite in pygame? For example, if the top of spri

4条回答
  •  野性不改
    2020-11-30 12:48

    The logic behind collision is like that:

    #Assume two surfaces
    objectA
    objectB
    
    if objectA.right > objectB.left and objectA.left < objectB.right and objectA.top < objectB.bottom and objectA.bottom > objectB.top
        #Collision happens
    

    if you want to detect side collision (as if objectA hitted objectB on the side) you can do the following:

    #Here is the code where objectA moves
    objectA.X += 10
    #Here check Collision, if collision happens objectA hitted objectB from the side
    objectA.Y += 10
    #Here check Collision again, if collision is true then objectA hitted object B from top/bottom
    

提交回复
热议问题