unity drag camera code example
Example 1: unity 2d Drag object
private Vector2 screenPoint;
private Vector3 offset;
void OnMouseDown() {
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector2(Input.mousePosition.x, Input.mousePosition.y));
}
void OnMouseDrag()
{
Vector2 curScreenPoint = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
Vector2 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
transform.position = curPosition;
}
Example 2: drag object unity 2d
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DragAndDrop : MonoBehaviour
{
private bool isDragging;
public void OnMouseDown()
{
isDragging = true;
}
public void OnMouseUp()
{
isDragging = false;
}
void Update()
{
if (isDragging) {
Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
transform.Translate(mousePosition);
}
}
}
Example 3: unity drag camera
if(Input.GetMouseButtonDown(0)) { bDragging = true; oldPos = transform.position; panOrigin = Camera.main.ScreenToViewportPoint(Input.mousePosition); //Get the ScreenVector the mouse clicked } if(Input.GetMouseButton(0)) { Vector3 pos = Camera.main.ScreenToViewportPoint(Input.mousePosition) - panOrigin; //Get the difference between where the mouse clicked and where it moved transform.position = oldPos + -pos * panSpeed; //Move the position of the camera to simulate a drag, speed * 10 for screen to worldspace conversion } if(Input.GetMouseButtonUp(0)) { bDragging = false; }