I have an object located at (208,608) in my 480x800 screen (portrait orientation). I can touch anywhere on the screen (where y < 608) and I will get touchX and touchY.

What is the angle I need to apply to my object so the it will face the point (touchX, touchY)?

I tried

double alfa = (float) Math.atan2(touchY-608,touchX-208) * 180 / PI;

but this doesn't seem to work if I touch one half of my screen. I also think this might be because the point is located in different quadrants reletive to my start point?

The angle I am trying to get is the angle determined by the two points and the horizontal axis from the first point. What I am trying to do is something like a bow facing my moving finger on the screen. Can anyone help me get the right angle please?

enter image description here

EDIT: I found the answer:

// Calculates an angle a body has to have to face a certain point in space

public static float rotateFromPointToPoint(float pFromPointX,float pFromPointY,float
                pToPointX,float pToPointY) {

        float k1 = (float) (pToPointY - pFromPointY);
        float k2 = (float) (pToPointX - pFromPointX);

        float tan = k1 / k2;

        float angle = (float) Math.atan(tan);
        float rotation = (float) Math.toDegrees(angle);

        if (pToPointX < pFromPointX) {
                rotation = (float) Math.toDegrees(angle) + 180;
        return rotation;

Maybe someone else will find this usefull.

  • \$\begingroup\$ you'd better post your answer as an answer, instead of editing it into the question. \$\endgroup\$ – o0'. Feb 2 '12 at 15:14
  • 2
    \$\begingroup\$ I don't have enough rep to do that.. I have to wait 7 more hours.. but I will np ;) \$\endgroup\$ – Fofole Feb 2 '12 at 15:35
  • \$\begingroup\$ Good, you will be upvoted for that: being neat is nice :) \$\endgroup\$ – o0'. Feb 2 '12 at 15:45
  • \$\begingroup\$ possible duplicate of Rotate object to face player \$\endgroup\$ – Nicol Bolas Feb 2 '12 at 17:13

atan2 is better than the code you post as an answer. What you need to do to the angle you get from atan2 will depend on what your drawing API considers to be the angle 0, but it's probably to add or subtract pi/2. One of the eight combinations of {-1, 1} * atan2(dy, dx) + {0, pi/2, pi, -pi/2} will work, so if you can't figure it out from first principles you could try all eight until you find the right one.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.