- Home /
Question by
JaredColl98 · Oct 24, 2012 at 09:07 PM ·
draw
Help : Need To Draw a Box
I need to know how to draw a box that starts at Input.GetMouseButtonDown(0) and continues to render and change size until Input.GetMouseButtonUp(0). And based on the mouse position. I cant figure out where to start.
Comment
Answer by phodges · Oct 24, 2012 at 09:47 PM
Here's an example to get you started:
using UnityEngine;
public class MouseBox : MonoBehaviour {
bool _isValid; //
bool _isDown;
Vector2 _mouseDownPos;
Vector2 _mouseLastPos;
// Update is called once per frame
void Update () {
// Detect when mouse button is down
if (Input.GetMouseButtonDown(0)) {
_mouseDownPos = Input.mousePosition;
_isDown = true;
_isValid = true;
}
// Continue tracking mouse position until the button is raised
if (_isDown) {
_mouseLastPos = Input.mousePosition;
if (Input.GetMouseButtonUp(0)) {
_isDown = false;
// If you want the box to vanish now, just set 'isValid' to false.
}
}
}
void OnGUI() {
if (_isValid) {
// Find the corner of the box
Vector2 origin;
origin.x = Mathf.Min(_mouseDownPos.x, _mouseLastPos.x);
// GUI and mouse coordinates are the opposite way around.
origin.y = Mathf.Max(_mouseDownPos.y, _mouseLastPos.y);
origin.y = Screen.height - origin.y;
//Compute size of box
Vector2 size = _mouseDownPos - _mouseLastPos;
size.x = Mathf.Abs(size.x);
size.y = Mathf.Abs(size.y);
// Draw it!
Rect r = new Rect(origin.x, origin.y, size.x, size.y);
GUI.Box(r, "");
}
}
}
I wrote it in javaScript but all the same it worked Thank you. Here is the code i used
var isValid : boolean;
var isDown : boolean;
var mouseLastPos : Vector2;
var mouseCurrentPos : Vector2;
function Update ()
{
if (Input.Get$$anonymous$$ouseButtonDown(0))
{
mouseLastPos.x = Input.mousePosition.x;
mouseLastPos.y = Input.mousePosition.y;
isDown = true;
isValid = true;
Debug.Log(mouseLastPos);
}
if(isDown)
{
mouseCurrentPos.x = Input.mousePosition.x;
mouseCurrentPos.y = Input.mousePosition.y;
if(Input.Get$$anonymous$$ouseButtonUp(0))
{
isDown= false;
isValid = false;
}
}
}
function OnGUI()
{
if(isValid)
{
var boxOrigin : Vector2;
var boxSize : Vector2;
boxOrigin.x = $$anonymous$$athf.$$anonymous$$in(mouseCurrentPos.x, mouseLastPos.x);
boxOrigin.y = $$anonymous$$athf.$$anonymous$$ax(mouseCurrentPos.y, mouseLastPos.y);
boxOrigin.y = Screen.height - boxOrigin.y;
boxSize = mouseLastPos - mouseCurrentPos;
boxSize.x = $$anonymous$$athf.Abs(boxSize.x);
boxSize.y = $$anonymous$$athf.Abs(boxSize.y);
GUI.Box(new Rect(boxOrigin.x, boxOrigin.y, boxSize.x, boxSize.y), "This is a box");
}
}
It looks like an accurate port of the C# I wrote. WIll you accept my answer?
Your answer
Follow this Question
Related Questions
How to draw 3D text from code 4 Answers
Draw to follow 5 Answers
Sudden frame rate drop during rendering 1 Answer
Grass not drawing past 1 metre 0 Answers
Draw a circle on touchscreen 1 Answer