- Home /
OnMouseDrag, how to make the object not move on the Y axis
Hello, i found a problem and don't know what to do. i am able to move my cube, but it goes in the Y axis and X and Z. i only want the cube to move in the X Z axis. how do i stop the cube going up?
using UnityEngine; using System.Collections;
[RequireComponent(typeof(BoxCollider))] [RequireComponent(typeof(MeshRenderer))]
public class DragRigidBody : MonoBehaviour { Vector3 screenPoint, offset, scanPos, curPosition, curScreenPoint;
public float gridSize = 0.20f;
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);
curPosition.z = (float)(Mathf.Round(curPosition.z) * gridSize);
transform.position = curPosition;
}
}
what do you mean? my camera doesnt move ingame,what do you mean? camera isn't moving at all.
In my opinion, offset containts value for Y axis and you are changing your curPosition with it. I think that is what moves with the object in Y axis in the end. $$anonymous$$aybe Im wrong, I can not really test it right now...
Answer by FM-Productions · Jun 01, 2017 at 01:43 PM
Simple:
store the original y position of your object in OnMouseDown:
yPosOriginal = gameObject.transform.position.y;
Then in OnMouseDrag() "Clamp" your gameObject to its original y position:
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);
curPosition.z = (float)(Mathf.Round(curPosition.z) * gridSize);
curPosition.y = yPosOriginal;
transform.position = curPosition;
}
Your answer
Follow this Question
Related Questions
Move and Rotate on a fixed axis? 1 Answer
Create Animation in unity3d only on one axis 0 Answers
move player to the grabPoint 2 Answers
Wrong Camera axis after "zoom" to GameObject 0 Answers
Lerp a Object along X and Z axis only. 3 Answers