Creating box that streches from point to mouse

I am trying to, on click and drag, create box a that has one corner at the origin and one point at where ever the mouse is like in the image bellow. A few seconds after the mouse is released it is destroyed. What is the cleanest way to do this? Do I need a box prefab, or is there some draw_box? And how do I specify the corners and have the box stretch accordingly?

After a little back-of-the-napkin math, I think you’re going to have to introduce another constraint. The two opposite points of a rectangle define one of the diagonals, but there are infinite rectangles with the same diagonal line.

Notice when you click and drag a box in any graphics editor (or Word even), the rectangle is always parallel to the edges of the screen. That constraint leaves you with only one rectangle (and looks like your third picture.)

If you decide that’s how you’d want to do it, then the other two points are easily calculated. Say your origin is P1, and the mouse is P2, The other two points have coordinates (P1.x, P2.y) and (P2.x, P1.y). After that you might could use a LineRenderer to draw all four points

An alternative constraint and solution is to use some fixed rectangle ratio (ie 1:3, where one side is 3 times as long as the other). Then you could have a default rectangle (which you know the diagonal length of) and then spawn it at your origin point (or offset to make the corner line up, I’m not sure how the spawning works…if it’s “Center” or “corner”.) Then you’d just rotate it to make the diagonal match, and then scale it up to make it the same length.


However, without knowing a little more about what you’re trying to do with this and how you want it to look, I can’t recommend one approach over the other