Calculating the angle between the line defined by two points

前端 未结 6 1192
我在风中等你
我在风中等你 2020-11-28 08:17

I\'m currently developing a simple 2D game for Android. I have a stationary object that\'s situated in the center of the screen and I\'m trying to get that object to rotate

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-28 08:20

    Had a need for similar functionality myself, so after much hair pulling I came up with the function below

    /**
     * Fetches angle relative to screen centre point
     * where 3 O'Clock is 0 and 12 O'Clock is 270 degrees
     * 
     * @param screenPoint
     * @return angle in degress from 0-360.
     */
    public double getAngle(Point screenPoint) {
        double dx = screenPoint.getX() - mCentreX;
        // Minus to correct for coord re-mapping
        double dy = -(screenPoint.getY() - mCentreY);
    
        double inRads = Math.atan2(dy, dx);
    
        // We need to map to coord system when 0 degree is at 3 O'clock, 270 at 12 O'clock
        if (inRads < 0)
            inRads = Math.abs(inRads);
        else
            inRads = 2 * Math.PI - inRads;
    
        return Math.toDegrees(inRads);
    }
    

提交回复
热议问题