• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

angle of mouse

 
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
im trying to get a sprite to fly towards the mouse when the left click is released. im having trouble figuring out how to get it to calculate the angle inwhich it needs to be moving in to fly towards mouse. anyone know how i could calculate this angle?
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The x and y components of the motion of the sprite are just going to be proportional to the x and y coordinate differences -- i.e.,

delta_x = f(mouse_x - sprite_x)
delta_y = f(mouse_y - sprite_y)

Where delta_x/y are the amounts to add to the x and y coordinates of the sprite in each frame of animation, mouse_x/y are the mouse coordinates, sprite_x/y are the sprite's coordinates, and f() is some function that determines the speed of motion -- it might be "divide by 5, rounding up", for example.

The actual angle isn't as useful, but if you truly need it, it's

angle_in_radians = Math.atan((mouse_y - sprite_y)/(mouse_x - sprite_x))

you need to be careful of that potential divide-by-zero; if the denominator is 0, then the angle is either 0 or pi, depending on the sign of the numerator.
 
Ranch Hand
Posts: 547
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Math.atan2(deltaY, deltaX) should do the trick. note that first argument is delta Y. it takes care of division by zero problems.
 
Did you ever grow anything in the garden of your mind? - Fred Rogers. Tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic