With the below code, I am able to click and drag an object, restricting said objects transforms to only X and Z. The issue is that when you drag the cube towards the edges of the screen, the object will either fall behind or go ahead of the mouse pointer, dependent on what “factor” I set. Is there a better way to have drag the cube around?
This is for a SimCity’ish type game I am creating: I want to be able to drag an object around, as well as have the ability to freely rotate the camera around.
var factor : float = 1.50;
private var objectStartPos : Vector3; // Initial position of object
private var mousePosition : Vector3; // Initial position of the mouse in world coordinates
private var baseZDistance : float; // Base Z distance to use in conversion
function OnMouseDown(){
objectStartPos = transform.localPosition;
var worldScreenPoint : Vector3 = Camera.main.WorldToScreenPoint(objectStartPos);
baseZDistance = worldScreenPoint.z;
mousePosition = new Vector3 (Input.mousePosition.x, Input.mousePosition.y, baseZDistance);
mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
}
function OnMouseDrag(){
worldScreenPoint = new Vector3 (Input.mousePosition.x, Input.mousePosition.y, baseZDistance);
worldScreenPoint = Camera.main.ScreenToWorldPoint(worldScreenPoint);
var worldScreenPoint2 : Vector3 = objectStartPos;
worldScreenPoint2 = objectStartPos;
worldScreenPoint2.x = Mathf.Round(worldScreenPoint2.x + (worldScreenPoint.x - mousePosition.x) / 2) * 2;
worldScreenPoint2.z = Mathf.Round(worldScreenPoint2.z + (worldScreenPoint.z - mousePosition.z) / 2) * 2;
transform.localPosition = worldScreenPoint2;
}