How to create an object and resize it with mouse drag???

Hey Everyone,

I know this question is asked many many so many times :wink: … Searching all day long unfortunatly I still couldn’t find what I want…

on left click I want to create an object on mouse position and I want to rescale it only on x axis (for ex: if obj. is created on left click and resize its x axis with on mouse drag )

Hope someone understood what I what :slight_smile:

(maybe)I have done Half of the work :

    using UnityEngine;
    using System.Collections;
    
    public class Cube : MonoBehaviour
    {
    		
    		public GameObject CubePrefab;
    
    void Update ()
    		{
    if (Input.GetMouseButtonDown (0)) {
    float positionZ = 10.0f;
 Vector3 position = new Vector3 (Input.mousePosition.x, Input.mousePosition.y,positionZ);
    
 Instantiate (CubePrefab, Camera.main.ScreenToWorldPoint (position),transform.rotation);
    
    				}}

this script is attached to main camera with a cubePrefab…
this creates an object but now how can I rescale it???

Best…
.J

2 Answers

2

Here is a bit of code that expands on your code. Note that the object growth will not map to the growing size, and note that, since it depends on screen coordinates, you will likely have to do something to recalculate ‘sizingFactor’ if you target multiple devices.

using UnityEngine;
using System.Collections;

public class Cube : MonoBehaviour {
		
	public GameObject cubePrefab;
	public float sizingFactor = 0.02f;
	private GameObject lastSpawn = null;
	private float startSize;
	private float startX;
		
	void Update () {
		if (Input.GetMouseButtonDown (0)) {
			float positionZ = 10.0f;
			Vector3 position = new Vector3 (Input.mousePosition.x, Input.mousePosition.y,positionZ);
			startX = position.x;
			position = Camera.main.ScreenToWorldPoint(position);
			lastSpawn = Instantiate (cubePrefab, position,transform.rotation) as GameObject;
			startSize = lastSpawn.transform.localScale.z;
		}

		if (Input.GetMouseButton (0)) {
			Vector3 size = lastSpawn.transform.localScale;
			size.x = startSize + (Input.mousePosition.x - startX) * sizingFactor;
			lastSpawn.transform.localScale = size;
		}
	}
}

Thanks @robertbu .. :) thanks a alot ... this solved my problem .. Now the object expands from both side what should I add to expand it only in one side.. Thanks again ...

–

thanks that formula really helped in a similar case resizing a quad with mouse drag nice
size.x = startSize + (Input.mousePosition.x - startX) * sizingFactor;