Open topic with navigation
Joystick or gamepad
\examples\input\tutorial_vizjoy.py
This script shows how to use a joystick or gamepad.
"""
Shows how to use a joystick or gamepad in your script.
Move the car with with the joystick and press any button to drop a ball.
"""
import sys
import viz
import vizact
viz.setMultiSample(4)
viz.fov(60)
viz.go()
import vizinfo
vizinfo.InfoPanel()
#Define constants
MOVE_SPEED = 10
TURN_SPEED = 90
# Connect to the first available joystick
dinput = viz.add('DirectInput.dle')
joy = dinput.addJoystick()
if not joy.valid():
sys.exit('Failed to detect a joystick')
# Set dead zone to ignore small movements
joy.setDeadZone(0.2)
#Add a ground
ground = viz.addChild('ground.osgb')
#Add a sky.
viz.addChild('sky_day.osgb')
#Initialize car and place view behind it
car = viz.addChild('mini.osgx')
#Link viewpoint to car
ViewCarLink = viz.link(car,viz.MainView)
#Apply operators to link so that view follows car from behind
ViewCarLink.preEuler( [0,10,0] )
ViewCarLink.preTrans( [0,0,-10] )
ViewCarLink.preEuler( [0,-10,0] )
#Load ball model to drop behide car
ball = viz.addChild('beachball.osgb')
ball.visible(False)
#Update position of car every frame
def updateCar():
#Get joystick position and elapsed time
elapsed = viz.elapsed()
x,y,z = joy.getPosition()
#Use y position of joystick to compute forward car movement
forwardMovementAmount = elapsed * MOVE_SPEED * y
car.setPosition( [ 0, 0, forwardMovementAmount], viz.REL_LOCAL )
#Use x position of joystick to compute how much the car should turn
rotationAmount = elapsed * TURN_SPEED * x
car.setEuler( [ rotationAmount, 0 , 0 ] , viz.REL_LOCAL )
vizact.ontimer(0,updateCar)
#Drop a all on the car's position when a joystick button is pressed
def joyDown(e):
if e.object is joy:
clone = ball.clone(pos=car.getPosition())
vizact.addCallback(viz.SENSOR_DOWN_EVENT, joyDown)