- Home /
Question by
MontyMomentum · Aug 11, 2020 at 10:17 AM ·
positionmouseaxisdrag
Drag object along Z axis using mouse
I found a script online making it possible to drag an Object along the X axis, I've tried adapting this to the Z axis but it doesn't work.
The original script
using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
public class ClampPosition : MonoBehaviour
{
public Vector2 xValues;
void Update()
{
if (transform.position.x > xValues.y)
transform.position = new Vector3 (xValues.y, transform.position.y, transform.position.z);
else if (transform.position.x < xValues.x)
transform.position = new Vector3 (xValues.x, transform.position.y, transform.position.z);
}
}
My adaptation
using UnityEngine;
using System.Collections;
public class clampPosZ : MonoBehaviour { public Vector2 ZValues;
public float dragSpeed = 1f; Vector3 lastMousePos;
void OnMouseDown()
{
lastMousePos = Input.mousePosition;
}
void OnMouseDrag()
{
Vector3 delta = Input.mousePosition - lastMousePos;
Vector3 pos = transform.position;
pos.z += delta.z * dragSpeed;
transform.position = pos;
lastMousePos = Input.mousePosition;
}
void Update()
{
if (transform.position.x > zValues.y)
transform.position = new Vector3(transform.position.x, transform.position.y, zValues.y);
else if (transform.position.x < zValues.x)
transform.position = new Vector3(transform.position.x, transform.position.y, zValues.x);
}
}
Comment
Best Answer
Answer by paddan · Aug 11, 2020 at 12:17 PM
You can't take the z delta from the cursor, because it's always going to be the same. The cursor only moves along x and y axis.
What you could do is apply the y delta to move your object along the z axis, which in your case would be: pos.z += delta.y * dragSpeed;