Hitesh Upadhyay
Hitesh Upadhyay

Reputation: 91

Distance between center to any point on edge of rectangle in javascript

enter image description here

As you can see in above picture, suppose that there is a ray emitted from center and collides at edge of rectangle. so I want to calculate at which point it collides, so that I could be able to calculate distance between point on edge and center.

Upvotes: 1

Views: 2632

Answers (2)

Kurbol
Kurbol

Reputation: 101

I found MBo's solution helpful for a game I'm working on in Unity3D. This is my adapted solution:

/// Returns the point on the edge of a rectangle in the given direction from the center
public static Vector2 PointOnRect(float radiusX, float radiusY, float radians)
{
  var normal = new Vector2(Mathf.Sin(radians), Mathf.Cos(radians));
  if (Mathf.Abs(normal.x * radiusY) > Mathf.Abs(normal.y * radiusX))
  {
    // Left or right
    var x = Mathf.Sign(normal.x) * radiusX;
    var cot = normal.y / normal.x;
    return new Vector2(x, x * cot);
  }
  else
  {
    // Top or bottom
    var y = Mathf.Sign(normal.y) * radiusY;
    var tan = normal.x / normal.y;
    return new Vector2(y * tan, y);
  }
}

Upvotes: 0

MBo
MBo

Reputation: 80187

Let's center is (0, 0) and ray angle is phi. Pseudocode:

c = Cos(phi)
s = Sin(phi)
if Width * Abs(s) < Height * Abs(c) then
   x = Sign(c) * Width / 2
   y = Tan(phi) * x
else
   y = Sign(s) * Height / 2
   x = CoTan(phi) * y

Upvotes: 4

Related Questions