Skip to content

Instantly share code, notes, and snippets.

@Boellis
Created March 19, 2019 07:17
Show Gist options
  • Save Boellis/4cb84c4c9a74e40cce2aa1c13f97cfeb to your computer and use it in GitHub Desktop.
Save Boellis/4cb84c4c9a74e40cce2aa1c13f97cfeb to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DragObject : MonoBehaviour {
private Vector3 mOffset;
private float mZCoord;
//private Vector3 currentPosition;
void OnMouseDown()
{
mZCoord = Camera.main.WorldToScreenPoint(gameObject.transform.position).z;
// Store offset = gameObject world pos - mouse world pos
mOffset = gameObject.transform.position - GetMouseWorldPos();
// currentPosition = gameObject.transform.position;
}
void OnMouseDrag()
{
transform.position = GetMouseWorldPos() + mOffset;
}
/*private void OnMouseUp()
{
transform.position = currentPosition;
}*/
private Vector3 GetMouseWorldPos()
{
//pixel coordinates (x,y)
Vector3 mousePoint = Input.mousePosition;
//z coordinate of game object on screen
mousePoint.z = mZCoord;
return Camera.main.ScreenToWorldPoint(mousePoint);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment