- Home /
Question by
therealFrEiz · May 09, 2017 at 06:11 AM ·
gameobjectmousepositionclonedrag-and-drop
Mouse drag cloning Game Objects
So I'm making a mario maker "clone" and I want it to instantiate objects when I hold control and drag. It makes almost infinite tiles. I want it to only make an object if the new position is the same as an old position of an object. Everything snaps to a grid of 1 by 1 blocks
public GameObject tilePrefab;
void OnMouseDrag(){
Vector2 pos = Input.mousePosition;
pos = Camera.main.ScreenToWorldPoint (pos);
pos.x = Mathf.Round(pos.x);
pos.y = Mathf.Round(pos.y);
transform.position = pos;
if (Input.GetKey (KeyCode.LeftControl)) {
if (transform.position != GameObject.Find ("SomePrefabName").transform.position) {
GameObject myGameObject = Instantiate (tilePrefab) as GameObject;
myGameObject.name = "SomePrefabName";
}
}
}
Comment
Best Answer
Answer by Piyush_Pandey · May 09, 2017 at 07:41 AM
If this is what you meant: I want it to only make an object if the new position is NOT the same as an old position of an object
You can use this code:
private Vector2 last_cachedPos;
void Start()
{
last_cachedPos = transform.position;
}
void OnMouseDrag() {
Vector2 pos = Input.mousePosition;
pos = Camera.main.ScreenToWorldPoint (pos);
pos.x = Mathf.Round(pos.x);
pos.y = Mathf.Round(pos.y);
if (pos!=last_cachedPos)
{
transform.position =last_cachedPos= pos;
if (Input.GetKey (KeyCode.LeftControl))
{
if (transform.position != GameObject.Find ("SomePrefabName").transform.position)
{
GameObject myGameObject = Instantiate (tilePrefab) as GameObject;
myGameObject.name = "SomePrefabName";
}
}
}}