- Home /
Instantiate and Scale with Mouse Click.
Hello Everyone, I have searched around and haven't been able to find quite what I am looking for. I understand how to instantiate an object where the mouse is clicked. However, I would like to implement more functionality.
Begin "drawing" object when left mouse button down. This would also act as an anchor/pivot point while the mouse is dragged around the screen.
Complete "drawing" object when left mouse button is released.
The object would scale only in its y while maintaining scale in both x and z. Any help would be greatly appreciated and I apologize if this has been answered elsewhere. Also, I would be writing this in C#
Answer by RyFridge · Jan 07, 2016 at 02:43 PM
Hey @BiffJenkins, I would use Input.mousePosition and Camera.ScreenPointToRay(). Try this script I just wrote and drop it on one of your Cameras:
[SerializeField] GameObject prefab;
[SerializeField] [Range(1f, 200f)] float drawDistance = 50f;
GameObject drawObject;
bool drawing = false;
Vector3 mouseStartingPosition;
Camera cam;
void Start(){
// load our camera
cam = GetComponent<Camera> ();
}
// Update is called once per frame
void Update () {
// check if we want to start, end, or continue drawing
if (Input.GetMouseButtonDown (0)) {
startDraw ();
} else if (Input.GetMouseButtonUp (0)) {
endDraw ();
} else if (drawing) {
whileDrawing ();
}
}
void startDraw(){
// create a new instance
drawObject = Instantiate (prefab, Vector3.zero, Quaternion.identity) as GameObject;
// save our draw starting point
mouseStartingPosition = Input.mousePosition;
// put the new instance where we pointed to with a set distance (or collision)
Ray ray = cam.ScreenPointToRay(mouseStartingPosition);
drawObject.transform.position = transform.position + ray.GetPoint (drawDistance);
// allow the Update to call whileDrawing()
drawing = true;
}
void endDraw(){
// forbid the Update do call whileDrawing()
drawing = false;
}
void whileDrawing(){
// manipulate the instance in whatever way you like
float mouseDistance = Vector3.Distance (mouseStartingPosition, Input.mousePosition);
drawObject.transform.localScale = new Vector3 (1f, mouseDistance, 1f);
}
Your answer
Follow this Question
Related Questions
Create objects on a mouse click in 2D 1 Answer
How to check for a mouse drag 0 Answers
Distribute terrain in zones 3 Answers
How do you Instantiate a button as a child object of a canvas? 0 Answers
Ensuring Correct Call Order 0 Answers