View Single Post
  #1  
Old 06-14-2009, 02:30 PM
Frank Verberne Frank Verberne is offline
Member
 
Join Date: Mar 2008
Location: Netherlands
Posts: 148
Collision of two boxes

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.
Code:
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.ORANGE,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.ORANGE,viz.PURPLE] ) )
	print e.obj1
	e.obj1.change_color()
		
viz.callback( viz.KEYBOARD_EVENT, onKeyboardEvent )
viz.callback( viz.COLLIDE_BEGIN_EVENT, onCollide )
Reply With Quote