Skip to content

Simple Collision Detection

Jonathan De Wachter edited this page May 14, 2016 · 1 revision

Overview

It is a port of the original SFML2 collision detection code.

This is a work-in-progress - only BoundingBoxTest has been implemented so far.

Code

To use this code save the following file and include it into your current Python-SFML project

Collision.py

import sfml as sf

class OrientedBoundingBox():
    def __init__(self, object):
        self.points = []

        trans = object.transform
        local = object.texture_rectangle
        self.points.append(trans.transform_point((0., 0.)))
        self.points.append(trans.transform_point((local.width, 0.)))
        self.points.append(trans.transform_point((local.width, local.height)))
        self.points.append(trans.transform_point((0., local.height)))

    def ProjectOntoAxis(self, axis):
        min = (self.points[0].x * axis.x+self.points[0].y*axis.y)

        max = min

        for i in range(4):
            projection = (self.points[i].x * axis.x+self.points[i].y*axis.y)

            if projection < min:
                min = projection
            if projection > max:
                max = projection

        return min, max

def BoundingBoxTest(object1, object2):
    OBB1 = OrientedBoundingBox(object1)
    OBB2 = OrientedBoundingBox(object2)

    axes = []
    axes.append(sf.Vector2(OBB1.points[1].x-OBB1.points[0].x, OBB1.points[1].y-OBB1.points[0].y))
    axes.append(sf.Vector2(OBB1.points[1].x-OBB1.points[2].x, OBB1.points[1].y-OBB1.points[2].y))
    axes.append(sf.Vector2(OBB2.points[0].x-OBB2.points[3].x, OBB2.points[0].y-OBB2.points[3].y))
    axes.append(sf.Vector2(OBB2.points[0].x-OBB2.points[1].x, OBB2.points[0].y-OBB2.points[1].y))

    for i in range(4):
        minOBB1, maxOBB1 = OBB1.ProjectOntoAxis(axes[i])
        minOBB2, maxOBB2 = OBB2.ProjectOntoAxis(axes[i])

        if not (minOBB2<=maxOBB1 and maxOBB2 >= minOBB1):
            return False

    return True
Clone this wiki locally