< Zurück | Inhalt | Weiter >

From the AvatarTest example, CarSteering.java


public class CarSteering extends Behavior

{

private WakeupOnAWTEvent wakeupOne = null;

private WakeupCriterion[] wakeupArray = new WakeupCriterion[1]; private WakeupCondition wakeupCondition = null;


private final float TRANSLATE_LEFT = −0.05f; private final float TRANSLATE_RIGHT = 0.05f;

TransformGroup m_TransformGroup = null; public CarSteering( TransformGroup tg )

{

m_TransformGroup = tg;


wakeupOne = new WakeupOnAWTEvent(KeyEvent.KEY_PRESSED); wakeupArray[0] = wakeupOne;

wakeupCondition = new WakeupOr(wakeupArray);

}


//Override Behavior's initialize method to set up wakeup criteria public void initialize()

{

//Establish initial wakeup criteria wakeupOn(wakeupCondition);

}

//Override Behavior's stimulus method to handle the event. public void processStimulus(Enumeration criteria)

{

WakeupOnAWTEvent ev; WakeupCriterion genericEvt; AWTEvent[] events;


while (criteria.hasMoreElements())

{

genericEvt = (WakeupCriterion) criteria.nextElement();


if (genericEvt instanceof WakeupOnAWTEvent)

{

ev = (WakeupOnAWTEvent) genericEvt; events = ev.getAWTEvent(); processAWTEvent(events);

}

}


//Set wakeup criteria for next time wakeupOn(wakeupCondition);

}


//Process a keyboard event

private void processAWTEvent(AWTEvent[] events)

{

for( int n = 0; n <events.length; n++)

{

if( events[n] instanceof KeyEvent)

{

KeyEvent eventKey = (KeyEvent) events[n];


if( eventKey.getID() == KeyEvent.KEY_PRESSED )

{

int keyCode = eventKey.getKeyCode(); int keyChar = eventKey.getKeyChar();


Vector3f translate = new Vector3f();


Transform3D t3d = new Transform3D(); m_TransformGroup.getTransform( t3d ); t3d.get( translate );


switch (keyCode)

{

case KeyEvent.VK_LEFT: translate.x += TRANSLATE_LEFT;

break;


case KeyEvent.VK_RIGHT: translate.x += TRANSLATE_RIGHT;

break;

}


t3d.setTranslation( translate ); m_TransformGroup.setTransform( t3d );

}

}

}

}

}


image

Writing custom behaviors is covered in greater detail in chapter 13.