Advertisement
Guest User

Untitled

a guest
Feb 21st, 2019
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. // rectangle x, y position
  2. var x = 400; // starting x position
  3. var y = 250; // starting y position
  4. var FPS = 60; // frames per second of the screen
  5. // physics variables:
  6. var velX = 0; // initial velocity at 0 (not moving)
  7. var velY = 0; // not moving
  8. var drag = 0.92; // drag force reduces velocity by 8% per frame
  9. var force = 0.35; // overall force applied to move the rectangle
  10. var angle = 0; // angle in which to move
  11.  
  12. // called every frame (at 60 frames per second):
  13. function update(){
  14. // calculate distance between mouse and rectangle
  15. var dx = mouseX - x;
  16. var dy = mouseY - y;
  17. // calculate angle between mouse and rectangle
  18. var angle = Math.atan(dy/dx);
  19. if(dx < 0)
  20. angle += Math.PI;
  21. else if(dy < 0)
  22. angle += 2*Math.PI;
  23.  
  24. // calculate the force (on or off, depending on user input)
  25. var curForce;
  26. if(keys[32]) // SPACE bar
  27. curForce = force; // if pressed, use 0.35 as force
  28. else
  29. curForce = 0; // otherwise, force is 0
  30.  
  31. // increment velocty by the force, and scaled by drag for x and y
  32. velX += curForce * Math.cos(angle);
  33. velX *= drag;
  34. velY += curForce * Math.sin(angle);
  35. velY *= drag;
  36.  
  37. // update x and y by their velocities
  38. x += velX;
  39. y += velY;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement