- Home /
touch to instantiate and move object ?
when i touch my screen is instantiate object maybe like quad or cube and i can move thats object if i never release my touch, but if i released my touch thats object is cant move again. and if i give touch again, im instantiate and move object always. how can i try this? because when i make script at camera like OnMouseDown its cant work? thankyou
Answer by CorruptedTNC · Dec 13, 2014 at 02:04 PM
Touching to spawn objects is not really something you want to happen if you want to be able to move placed objects later on. Here's what I would do personally:
Have buttons that spawn different Game Objects and then keep a reference for them for example:
public GameObject curObject;
public LayerMask objLayer;
if(GUILayout.Button("Spawn Cube"))
{
curObject = GameObject.CreativePrimitive(PrimitiveType.Cube);
}
Touch controls come with phases, which give you access to information similar to events, which you can use as follows:
void Update()
{
//This will get the first touch available when the finger is moving
if (Input.GetTouch(0).phase == TouchPhase.Moved && curObject != null)
{
//This may be incorrect, I don't have Unity in front of me.
//If this is wrong, look at transforming this to a world co-ordinate.
curObject.transform.position = Input.GetTouch(0).Position;
}
//The finger has left the screen and we have a curObject that we were moving
if(Input.GetTouch(0).phase == TouchPhase.Ended && curObject != null)
{
//Set up a layer specifically for movable GameObjects and set that
//layer number here, you'll see why in a second
curObject.Layer = 6;
//We're done with the current object, so our reference to it must now be
//removed
curObject = null;
}
//We don't have a current object, time to find one
if (Input.GetTouch(i).phase == TouchPhase.Began && curObject == null)
{
// Construct a ray from the current touch coordinates
Ray ray = Camera.main.ScreenPointToRay (Input.GetTouch(i).position);
RaycastHit hit;
if (Physics.Raycast (ray, out hit, Mathf.Infinity, objLayer))
{
//We've hit something, information is in the RaycastHit object.
curObject = hit.transform.GameObject;
}
}
}
Things for you to read: Raycast information RaycastHit information Layers and LayerMasks