PDA

View Full Version : Collision of two boxes


Frank Verberne
06-14-2009, 02:30 PM
I'm trying to figure out how to improve some old code by using classes. The current situation is that I try to collide two boxes (box1 and box2) and after collision, box2 should change color. Now I can get this working by calling e.obj1.color() in the collide function, but I would like to use the change_color() function I defined in the class. My question is why e.obj1.change_color() doesn't work. As I see it, e.obj1 refers to box2, which is an instance of the class make_box(). But when I print e.obj1, I get something different than when I print box2, indicating that they are not the same. So I think the problem is in how the collide function works, but I don't know how to get e.obj1 to work with the method I defined for box2. See below for my code. The keys w, a, s, d move box1 around, to be able to collide with box2.
import viz
import random

viz.go()

viz.add('gallery.ive')
viz.phys.enable()

class make_box:
def __init__(self, pos, name):
self.obj = viz.add('box.wrl')
self.obj.setPosition(pos)
self.obj.name = name
self.obj.scale([.1]*3)
self.obj.color(viz.WHITE)
self.obj.collideBox()
self.obj.disable(viz.DYNAMICS)
self.obj.enable(viz.COLLIDE_NOTIFY)

def change_color(self):
color = random.choice( [viz.RED,viz.GREEN,viz.SKYBLUE,viz.YELLOW,viz.ORANG E,viz.PURPLE] )
self.obj.color(color)

global x, y ,z, box1, box2
x = 0
y = 0
z = 0

box1 = viz.add('box.wrl')
box1.name = 'test!'
box1.scale([.1,.1,.1])
box1.collideBox()
box1.disable(viz.DYNAMICS)

box2 = make_box([0,.30,0], 'Left')
print box2

def onKeyboardEvent(key):
global box1, box2, x, y, z
if key in 'wW':
y = y+.1

elif key in 'aA':
x = x - .1

elif key in 'sS':
y = y - .1

elif key in 'dD':
x = x + .1

elif key == viz.KEY_PAGE_UP:
z = z + .1

elif key == viz.KEY_PAGE_DOWN:
z = z - .1

elif key in 'cC':
box2.change_color()

box1.setPosition([x,y,z])

def onCollide(e):
print "boxes collided!"
e.obj1.color(random.choice( [viz.RED,viz.GREEN,viz.SKYBLUE,viz.YELLOW,viz.ORANG E,viz.PURPLE] ) )
print e.obj1
e.obj1.change_color()

viz.callback( viz.KEYBOARD_EVENT, onKeyboardEvent )
viz.callback( viz.COLLIDE_BEGIN_EVENT, onCollide )

Gladsomebeast
06-15-2009, 02:22 PM
As your print statements point out, e.obj1 is not box2. e.obj1 is the box.wrl VizNode object you created in the make_box constructor.

The solution is to have make_box inherent from VizNode. This Vizard help page shows how to do that:
http://www.worldviz.com/vizhelp/Structuring_Vizard_scripts.htm

It also has a link to an object oriented Python tutorial I suggest you check out:
http://www.freenetpages.co.uk/hp/alan.gauld/tutclass.htm

Frank Verberne
06-23-2009, 07:42 AM
Thanks for your reply! Having make_box inheret from VizNode did the trick. The link to the object oriented Python tutorial was helpful as well.

Gladsomebeast
06-23-2009, 09:52 AM
Glad to help. Especially to you, who is wise to invest in improving your code.