From 973988b911037cef97f11c37f3a02018b45e2b98 Mon Sep 17 00:00:00 2001 From: Quantum Date: Fri, 21 Feb 2014 12:45:33 -0500 Subject: [PATCH] Added collision; bounces on collision. --- punyverse/entity.py | 19 ++++++++++++++++++- punyverse/game.py | 4 ++++ punyverse/world.py | 2 +- 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/punyverse/entity.py b/punyverse/entity.py index 50ef295..4b4ea87 100644 --- a/punyverse/entity.py +++ b/punyverse/entity.py @@ -1,5 +1,6 @@ -from punyverse.orbit import KeplerOrbit +from math import sqrt +from punyverse.orbit import KeplerOrbit from pyglet.gl import * @@ -15,6 +16,9 @@ class Entity(object): x, y, z = self.location dx, dy, dz = self.direction self.location = x + dx, y + dy, z + dz + + def collides(self, x, y, z): + return False class Asteroid(Entity): @@ -48,6 +52,7 @@ class Body(Entity): self.corona = kwargs.pop('corona', 0) self.last_tick = 0 self.mass = kwargs.pop('mass', None) + self.radius = kwargs.pop('radius', None) self.world = kwargs.pop('world') orbit_distance = kwargs.pop('orbit_distance', 40000) + .0 self.orbit_show = orbit_distance * 1.25 @@ -64,6 +69,18 @@ class Body(Entity): pitch, yaw, roll = self.rotation roll = (self.initial_roll + self.world.tick * self.rotation_angle) % 360 self.rotation = pitch, yaw, roll + + def collides(self, x, y, z): + if self.radius is None: + return False + ox, oy, oz = self.location + dx, dy, dz = x - ox, y - oy, z - oz + distance = sqrt(dx*dx + dy*dy + dz*dz) + if distance > self.radius: + return False + return (ox + dx * self.radius / distance, + oy + dy * self.radius / distance, + oz + dz * self.radius / distance) class Satellite(Body): diff --git a/punyverse/game.py b/punyverse/game.py index 637ceb3..bea4452 100644 --- a/punyverse/game.py +++ b/punyverse/game.py @@ -351,6 +351,10 @@ class Applet(pyglet.window.Window): self.world.tick += update for entity in self.world.tracker: entity.update() + collision = entity.collides(c.x, c.y, c.z) + if collision: + self.speed *= -1 + c.move(self.speed * 12 * dt) else: self.__time_accumulate += delta diff --git a/punyverse/world.py b/punyverse/world.py index ef388ff..e4f8194 100644 --- a/punyverse/world.py +++ b/punyverse/world.py @@ -190,7 +190,7 @@ class World(object): print 'Nothing to load for %s.' % name return - params = {'world': self, 'orbit_distance': orbit_distance} + params = {'world': self, 'orbit_distance': orbit_distance, 'radius': None if background else radius} if parent is None: type = Body else: