- Home /
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?
Answer by perchik · Oct 04, 2013 at 01:56 PM
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
I am essentially trying to recreate the line/trail renderer. I found that they didn't give me all of the control that I need so I thought that you could click and drag to create squares, sort of creating a chain to create a trail from the origin to the mouse.
Your answer
Follow this Question
Related Questions
instatiate gameobject after 1 second 1 Answer
Checking if object intersects? 1 Answer
Get unity to recognize prefab in C# 2 Answers
Instantiated object rotation abruptly. 0 Answers