In our last tutorials we saw how to detect planes and place objects on them. In this tutorial, we will see how to scale the placed object using pinch zoom.
If you have not read our previous tutorials then you can find them below
How to Detect Pinch in Touch screen and apply to scale?
Unity Touch count function returns the number of touches on the screen. To detect pinch we need to follow these steps
- Check if the touch count is greater than 1.
- Calculate the distance between two touches.
- See if the distance is increasing or decreasing.
- Assign the distance value to object scale.
We will be using Unity’s default input system for this tutorial.
Now lets modify the object placement script
Pinch to zoom AR object script
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR.ARSubsystems;
public class Raycast_script : MonoBehaviour
{
public GameObject spawn_prefab;
GameObject spawned_object;
bool object_spawned;
ARRaycastManager arrayman;
Vector2 First_touch;
Vector2 second_touch;
float distance_current;
float distance_previous;
bool first_pinch=true;
List <ARRaycastHit> hits=new List<ARRaycastHit>();
// Start is called before the first frame update
void Start()
{
object_spawned=false;
arrayman=GetComponent<ARRaycastManager>();
}
// Update is called once per frame
void Update()
{
if(Input.touchCount>0 && !object_spawned)
{
if(arrayman.Raycast(Input.GetTouch(0).position,hits,TrackableType.PlaneWithinPolygon))
{
var hitpose=hits[0].pose;
spawned_object=Instantiate(spawn_prefab,hitpose.position,hitpose.rotation);
object_spawned=true;
}
}
if(Input.touchCount>1 && object_spawned)
{
First_touch=Input.GetTouch(0).position;
second_touch=Input.GetTouch(1).position;
distance_current=second_touch.magnitude-First_touch.magnitude;
if(first_pinch)
{
distance_previous=distance_current;
first_pinch=false;
}
if(distance_current!=distance_previous)
{
Vector3 scale_value=spawned_object.transform.localScale*(distance_current/distance_previous);
spawned_object.transform.localScale=scale_value;
distance_previous=distance_current;
}
}
else{
first_pinch=true;
}
}
}
If you have not followed our previous tutorial then just create a new script with name “Raycast_script” and copy and paste the above code.
Attach the script to your ARsessionorigin.
If you have any other question on this tutorial, please leave a comment below.