ActionScript 3.0 Design Patterns

(Chris Devlin) #1
Example: Animating Composite Objects Using Inverse Kinematics | 227

Line 26 in theMainclass (Example 6-14) registers theonKeyPresshandler method to


respond toKey_DOWNevents. The left and right arrow keys make the snake head rotate


counter-clockwise and clockwise by 10 degrees. The up and down arrow keys make


the snake head move forward or back by 5 pixels. ThePoint.polarmethod comes in


handy here, as the snake needs to move in the direction that it’s facing (rotation


angle). ThePoint.polar()method returns a point that is the distance and angle from


the origin (0, 0). Adding the coordinates of this point (xandyproperties of thePoint


class) to the current location gives us the new location.


Before developing the body segments of the snake, we need to explore how a kine-


matic chain works.


23 addChild(snake);
24
25 // register with the stage to receive key press events
26 stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPress);
27 }
28
29 private function onKeyPress(event:KeyboardEvent):void
30 {
31 switch (event.keyCode)
32 {
33 case Keyboard.LEFT :
34 snake.rotation -= 10;
35 break;
36 case Keyboard.RIGHT :
37 snake.rotation += 10;
38 break;
39 case Keyboard.UP :
40 var newFWLocOffset:Point = Point.polar(5, snake.rotation * Math.PI / 180);
41 snake.x += newFWLocOffset.x;
42 // move forward by the x offset
43 snake.y += newFWLocOffset.y;
44 // move forward by the y offset
45 break;
46 case Keyboard.DOWN :
47 var newBKLocOffset:Point = Point.polar(5, snake.rotation * Math.PI / 180);
48 snake.x -= newBKLocOffset.x;
49 // move back by the x offset
50 snake.y -= newBKLocOffset.y;
51 // move back by the y offset
52 break;
53 }
54 }
55 }
56 }

Example 6-14. Main.as

Free download pdf