Unity Tutorial: How to drag an object in AR, but keep it on the ground plane
This C# script is a modification of the fantastic Lean Touch Unity asset which lets you drag an object around in AR using your finger, and the prefab will stay on the ground plane. It took me a little while to figure it out so hopefully this can help someone else starting out.
The issue with just using the original Lean Touch script is that it moves the object around in 3 dimensions, resulting in floating objects. This modified version locks the vertical axis to zero so that the prefab stays on the AR plane.
To use this script just drag it onto the object you want to move.
Here it is:
— — — — — — — — — — — — — — — — — — — — — — — — — — — — —
using UnityEngine;
namespace Lean.Touch
{
// This script allows you to transform the current GameObject with smoothing
public class LeanTranslateSmooth : LeanTranslate
{
[Tooltip(“How smoothly this object moves to its target position”)]
public float Dampening = 10.0f;
// The position we still need to add
[HideInInspector]
public Vector3 RemainingDelta;
protected virtual void LateUpdate()
{
// Get t value
var factor = LeanTouch.GetDampenFactor(Dampening, Time.deltaTime);
// Dampen remainingDelta
var newDelta = Vector3.Lerp(RemainingDelta, Vector3.zero, factor);
// Shift this transform by the change in delta(Atul`s change)
Vector3 moveMe = (RemainingDelta — newDelta);
moveMe.z = moveMe.y;
moveMe.y = 0f;
//transform.position += (RemainingDelta — newDelta);
transform.position += moveMe;
// Debug.Log(“pos : “+transform.position);
// Update remainingDelta with the dampened value
RemainingDelta = newDelta;
}
protected override void Translate(Vector2 screenDelta)
{
// Make sure the camera exists
var camera = LeanTouch.GetCamera(Camera, gameObject);
if (camera != null)
{
// Store old position
var oldPosition = transform.position;
// Screen position of the transform
var screenPosition = camera.WorldToScreenPoint(oldPosition);
// Add the deltaPosition
screenPosition += (Vector3)screenDelta;
// Convert back to world space
var newPosition = camera.ScreenToWorldPoint(screenPosition);
// Add to delta
RemainingDelta += newPosition — oldPosition;
}
}
}
}