Vizard 7 » Tutorials & Examples » Example scripts » Input Devices » Joystick
7.6

Joystick

\examples\input\joystick.py

This script demonstrates how to connect to a joystick device and handle state changes.

"""
This script demonstrates how to connect to
a joystick device and handle state changes.
The axes control the view position/rotation
and the trigger button resets the view.
"""
import sys
import viz
import vizact
import vizconfig

viz.setMultiSample(4)
viz.fov(60)
viz.go()

import vizinfo
vizinfo.InfoPanel()

# Get list of joystick device information
dinput = viz.add('DirectInput.dle')
devices = dinput.getJoystickDevices()

# Exit if no joystick detected
if not devices:
    sys.exit('No joystick devices connected')

# If there is more than one device, then display selection dialog
if len(devices) > 1:
    selected = viz.choose('Select joystick device', [ d.productName for d in devices ])
else:
    selected = 0

# Connect to selected device
joy = dinput.addJoystick(devices[selected])
if not joy:
    sys.exit('Failed to connect to joystick')

# Set dead zone threshold so small movements of joystick are ignored
joy.setDeadZone(0.2)

# Display joystick information in config window
vizconfig.register(joy)
vizconfig.getConfigWindow().setWindowVisible(True)

# Create node for applying joystick movement and link to main view
joystick_node = viz.addGroup(pos=(0,1.8,0))
viz.link(joystick_node, viz.MainView)

# Use joystick axes to move joystick node
# Horizontal (X) axis controls yaw
# Vertical (Y) axis controls position
MOVE_SPEED = 5.0
TURN_SPEED = 90.0
def UpdateJoystickMovement():
    e = viz.elapsed()
    x,y,= joy.getPosition()
    joystick_node.setEuler([* TURN_SPEED * e, 0, 0], viz.REL_LOCAL)
    joystick_node.setPosition([0, 0, y * MOVE_SPEED * viz.getFrameElapsed()], viz.REL_LOCAL)
vizact.ontimer(0, UpdateJoystickMovement)

# Reset joystick when joystick button 0 is pressed
def ResetPosition():
    joystick_node.setPosition([0,1.8,0])
    joystick_node.setEuler([0,0,0])
vizact.onsensordown(joy, 0, ResetPosition)

# Add environment
viz.addChild('maze.osgb')