Avatar.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. // CONSTANTS
  2. var MAX_VELOCITY = 2;
  3. var node = self.node;
  4. var animationSet = cache.getResource("AnimationSet2D", "Spriter.scml");
  5. var sprite = node.createComponent("AnimatedSprite2D");
  6. sprite.setAnimation(animationSet, "Idle");
  7. sprite.setLayer(100);
  8. node.setPosition([8, 14, 0]);
  9. node.scale2D = [.25, .25];
  10. var body = node.createComponent("RigidBody2D");
  11. body.setBodyType(Atomic.BT_DYNAMIC);
  12. body.fixedRotation = true;
  13. var circle = node.createComponent("CollisionCircle2D");
  14. // Set radius
  15. circle.setRadius(2);
  16. // Set density
  17. circle.setDensity(1.0);
  18. // Set friction.
  19. circle.setFriction(1);
  20. // Set restitution
  21. circle.setRestitution(0.1);
  22. var anim = "Idle";
  23. var flipped = false;
  24. function handleAnimation() {
  25. var vel = body.linearVelocity;
  26. if (vel[0] < -0.1) {
  27. if (!flipped) {
  28. sprite.flipX = true;
  29. flipped = true;
  30. }
  31. if (anim != "Run") {
  32. sprite.setAnimation(animationSet, "Run");
  33. anim = "Run";
  34. }
  35. } else if (vel[0] > 0.1) {
  36. if (flipped) {
  37. sprite.flipX = false;
  38. flipped = false;
  39. }
  40. if (anim != "Run") {
  41. sprite.setAnimation(animationSet, "Run");
  42. anim = "Run";
  43. }
  44. } else {
  45. if (anim != "Idle") {
  46. sprite.setAnimation(animationSet, "Idle");
  47. anim = "Idle";
  48. }
  49. }
  50. }
  51. function handleInput(timeStep) {
  52. var vel = body.linearVelocity;
  53. var pos = node.position2D;
  54. if (Math.abs(vel[0]) > MAX_VELOCITY) {
  55. vel[0] = (vel[0] ? vel[0] < 0 ? -1 : 1 : 0) * MAX_VELOCITY;
  56. body.setLinearVelocity(vel);
  57. }
  58. var left = input.getKeyDown(Atomic.KEY_A);
  59. var right = input.getKeyDown(Atomic.KEY_D);
  60. var jump = input.getKeyDown(Atomic.KEY_SPACE);
  61. if (left && vel[0] > -MAX_VELOCITY) {
  62. body.applyLinearImpulse([-2, 0], pos, true);
  63. } else if (right && vel[0] < MAX_VELOCITY) {
  64. body.applyLinearImpulse([2, 0], pos, true);
  65. }
  66. if (!left && !right) {
  67. vel[0] *= 0.9;
  68. body.linearVelocity = vel;
  69. }
  70. if (jump) {
  71. vel[1] = 0;
  72. body.linearVelocity = vel;
  73. body.applyLinearImpulse([0, 4], pos, true);
  74. }
  75. }
  76. function postUpdate() {
  77. // may have to set this post update
  78. cameraNode.position = node.position;
  79. }
  80. function update(timeStep) {
  81. handleInput();
  82. handleAnimation();
  83. }