Jumping on a 2D Circle

Actionscript:
  1. var circle:Shape = Shape(addChild(new Shape()));
  2. with(circle.graphics) beginFill(0xCCCCCC), drawCircle(0,0,100);
  3. circle.x = stage.stageWidth / 2;
  4. circle.y = stage.stageHeight / 2;
  5.  
  6. var charWorld:MovieClip = MovieClip(addChild(new MovieClip()));
  7. charWorld.x = circle.x ;
  8. charWorld.y = circle.y - 100 - 10
  9. charWorld.thetaSpeed = 0;
  10. charWorld.theta  = -Math.PI / 2;
  11.  
  12. var char:MovieClip = MovieClip(charWorld.addChild(new MovieClip))
  13. with(char.graphics) beginFill(0x000000), drawRect(-10,-10,10,10);
  14. char.posY = 0;
  15. char.velY = 0;
  16.  
  17. addEventListener(Event.ENTER_FRAME, onRunChar);
  18. function onRunChar(evt:Event):void {
  19.    
  20.     char.velY += 1;
  21.     char.posY += char.velY;
  22.    
  23.     charWorld.thetaSpeed *= .6;
  24.     charWorld.theta += charWorld.thetaSpeed;
  25.    
  26.     if (key[Keyboard.UP]){
  27.         if (char.y == 0){
  28.           char.velY = -10;
  29.         }
  30.     }
  31.    
  32.     if (key[Keyboard.RIGHT]){
  33.         charWorld.thetaSpeed = .1;
  34.     }
  35.    
  36.     if (key[Keyboard.LEFT]){
  37.         charWorld.thetaSpeed = -.1;
  38.     }
  39.    
  40.     if (char.posY> 0){
  41.         char.posY = 0;
  42.     }
  43.    
  44.     char.y = char.posY;
  45.    
  46.     charWorld.x = circle.x + 100 * Math.cos(charWorld.theta);
  47.     charWorld.y = circle.y + 100 * Math.sin(charWorld.theta);
  48.     charWorld.rotation = Math.atan2(circle.y- charWorld.y, circle.x - charWorld.x) / Math.PI * 180 - 90;
  49. }
  50.  
  51. var key:Object = new Object();
  52. stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPressed);
  53. stage.addEventListener(KeyboardEvent.KEY_UP, onKeyReleased);
  54. function onKeyPressed(evt:KeyboardEvent):void {
  55.     key[evt.keyCode] = true;
  56.     key.keyCode = evt.keyCode;
  57. }
  58.  
  59. function onKeyReleased(evt:KeyboardEvent):void {
  60.     key[evt.keyCode] = false
  61. }

For some reason I felt like posting the swf.... have a look here.

This is one that's been kicking around in my head for awhile - finally got around to writing it. It creates a circle and a small black box. The box walks and jumps on the circle with key input (left arrow, right arrow and up arrow).

There's an odd trick going on here. Basically, the box (or char) movieClip is nested inside another clip. Within this clip (charWorld) the box moves on the y axis (jumping/up key). The charWorld clip orbits around the circle and rotates toward the center of the circle - sine/cosine are used for the orbit so the left and the right keys control the speed of theta.

This entry was posted in misc, motion and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*