Though I have managed to drag 2DCamera with my previous code which uses,
Camera.main.ScreenToWorldPoint(Input.mousePosition);
Problem starts when CinemachineConfiner with PolygonCollider2D is attached.
Camera perfectly stops at collider end while dragging, but after colliding when we try to drag it in opposite direction it takes sometime and then starts moving.
This happens because at collider end the dragging code only restrict transform values of MainCamera where as 2DCamera transform values keeps changing. When we start dragging in opposite direction it waits for 2DCamera transform values to match MainCamera’s.
So, which is the way to trigger event from Confiner/PolygonCollider2D in order to stop drag code?
Here is a complete code attached to a Cinemachine 2DCamera.
using UnityEngine;
public class DragCamera : MonoBehaviour
{
public Camera cam;
Vector3 camPos;
Vector3 hitStartPos;
bool drag;
Vector3 velocity = Vector3.zero;
// Start is called before the first frame update
void Start()
{
}
void LateUpdate()
{
if (Input.GetMouseButtonDown(0))
{
hitStartPos = cam.ScreenToWorldPoint(Input.mousePosition);
drag = false;
velocity = Vector3.zero;
}
if (Input.GetMouseButtonUp(0))
{
drag = false;
}
if (Input.GetMouseButton(0))
{
drag = true;
}
if (drag)
{
Vector3 target = hitStartPos - (CalcDistance(cam.ScreenToWorldPoint(Input.mousePosition), transform.position));
transform.position = Vector3.SmoothDamp(transform.position, target, ref velocity, Time.deltaTime * 5f, 10f, Time.deltaTime);
}
}
Vector3 CalcDistance(Vector3 a, Vector3 b)
{
Vector3 dist = a - b;
return dist;
}
}