DGKN
February 21, 2015, 5:41pm
1
Hi,
With the current code below, I can drag and snap an object but the movement is jerky as it calculates round coordinates to snap objects together. How can I make the dragging smoother ? Thanks !
Here’s the code :
void OnMouseDown()
{
scanPos = gameObject.transform.position;
screenPoint = Camera.main.WorldToScreenPoint(scanPos);
offset = scanPos - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}
void OnMouseDrag()
{
curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
curPosition.x = (float)(Mathf.Round(curPosition.x / gridSize_x) * gridSize_x);
curPosition.y = (float)(Mathf.Round(curPosition.y / gridSize_y) * gridSize_y);
curPosition.z = (float)(Mathf.Round(curPosition.z / gridSize_z) * gridSize_z);
transform.position = curPosition;
}
Mmmpies
February 21, 2015, 5:53pm
2
Don’t know if this helps but I put together a basic Kerbal Space Program test a while ago. Scripts are in the package:
SnapDrag
Might be some unused scripts in there as well and as ever, it was OK when it left me but virus check it as it’s been on the Internet.
EDIT
Ah OK, the DragWithMouse script is years old, it doesn’t do snapping but will drag something smoothly.
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(MeshCollider))]
public class DragWithMouse : MonoBehaviour
{
private Vector3 screenPoint;
private Vector3 offset;
public bool IsDragable = true;
void OnMouseDown()
{
if(IsDragable) // Only do if IsDraggable == true
{
screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}
}
void OnMouseDrag()
{
if(IsDragable) // Only do if IsDraggable == true
{
Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
transform.position = curPosition;
}
}
}