I think the best solution is to add a velocity attribute to your actor ("character", or "Camera" in your example?). Then depending on the collision, zero out a velocity attribute.
Given a simple vector class like this one:
class Vector(object):
def __init__(self, x=0.0, y=0.0, z=0.0):
self.x = x
self.y = y
self.z = z
... your actor then looks like this:
class Actor(object):
def __init__(self):
self.pos = Vector()
self.vel = Vector()
Now when you update your scene, perform the following steps (abstracted to your example):
- Calculate the forces exerted on your actor, and update the
vel
attribute. - Determine collisions, and update the
vel
attribute accordingly. - Update the actor's
pos
with the data fromvel
.
The below example uses a 2D world for simplicity (z
is always 0
), and a constant timestep of updating (dt
is considered 1 second).
class Actor(object):
#(...)
def update(self, dt=1):
# Step 1 - assumes a constant movement to the top right
self.vel.x = 1
self.vel.y = 1
# Step 2 - cube is your collision tested object
cube = Cube()
new_pos = self.pos + (self.vel * dt)
if new_pos.x > cube.left and new_pos.x < cube.right:
self.vel.x = 0
if new_pos.y > cube.bottom and new_pos.y < cube.top:
self.vel.y = 0
# Step 3
self.pos += self.vel * dt
First you should get something like this working. When functioning as it should, add a bounding box to your actor so that the collision is performed on the sides instead of on the center.