Skip to content
Advertisement

Finding points on a rectangle at a given angle

I’m trying to draw a gradient in a rectangle object, with a given angle (Theta), where the ends of the gradient are touching the perimeter of the rectangle.

Graph

I thought that using tangent would work, but I’m having trouble getting the kinks out. Is there an easy algorithm that I am just missing?

End Result

So, this is going to be a function of (angle, RectX1, RectX2, RectY1, RectY2). I want it returned in the form of [x1, x2, y1, y2], so that the gradient will draw across the square. In my problem, if the origin is 0, then x2 = -x1 and y2 = -y1. But it’s not always going to be on the origin.

Advertisement

Answer

Let’s call a and b your rectangle sides, and (x0,y0) the coordinates of your rectangle center.

You have four regions to consider:

alt text

    Region    from               to                 Where
    ====================================================================
       1      -arctan(b/a)       +arctan(b/a)       Right green triangle
       2      +arctan(b/a)        π-arctan(b/a)     Upper yellow triangle
       3       π-arctan(b/a)      π+arctan(b/a)     Left green triangle
       4       π+arctan(b/a)     -arctan(b/a)       Lower yellow triangle

With a little of trigonometry-fu, we can get the coordinates for your desired intersection in each region.

alt text

So Z0 is the expression for the intersection point for regions 1 and 3
And Z1 is the expression for the intersection point for regions 2 and 4

The desired lines pass from (X0,Y0) to Z0 or Z1 depending the region. So remembering that Tan(φ)=Sin(φ)/Cos(φ)


    Lines in regions      Start                   End
    ======================================================================
       1 and 3           (X0,Y0)      (X0 + a/2 , (a/2 * Tan(φ))+ Y0
       2 and 4           (X0,Y0)      (X0 + b/(2* Tan(φ)) , b/2 + Y0)

Just be aware of the signs of Tan(φ) in each quadrant, and that the angle is always measured from THE POSITIVE x axis ANTICLOCKWISE.

HTH!

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement