- Home /
Mouse drag with specific angle
Hi, im trying to do mouse drag with specific angle. I have some cube, and wall (look picture).. and i want that cube will follow to wall with my mouse drag on X and Z axis.. white cube is wall black cube is a cube - when i want to drag... any idea? i have the script "MouseDrag"...
function OnMouseDown()
{
screenPoint =Camera.main.WorldToScreenPoint(scanPos);
offset = scanPos -Camera.main.ScreenToWorldPoint(Vector3(Input.mousePosition.x,Input.mousePosition.y,screenPoint.z));
}
function OnMouseDrag()
{
curScreenPoint =newVector3(Input.mousePosition.x,Input.mousePosition.y, screenPoint.z);
curPosition =Camera.main.ScreenToWorldPoint(curScreenPoint)+ offset;
transform.position = curPosition;
}
Here is picture
Kind regards Thomas
Answer by robertbu · Aug 23, 2014 at 04:24 PM
It would be easiest if you defined this problem as confinging an object to an arbitrary line rather than a specific angle. From your drawing, the easiest way to get the line would be to add an empty game object to your wall at a point other than the pivot point and at the same distance from the camera. Then you can define the line by a point and a direction. For dragging, you can find the closest point on the line to the mouse cursor, and position your block at that position. The closest position on the line can be done using Using the ProjectPointOnLine() method in the Math3d class in the Unity Wiki. So given 'scanPos' is the position of your wall, and that 'secondPos' is the Transform of an empty game object on the wall that defines the line, here is a bit of untested changes to your code:
function OnMouseDown()
{
screenPoint =Camera.main.WorldToScreenPoint(scanPos);
offset = scanPos -Camera.main.ScreenToWorldPoint(Vector3(Input.mousePosition.x,Input.mousePosition.y,screenPoint.z));
}
function OnMouseDrag()
{
curScreenPoint =newVector3(Input.mousePosition.x,Input.mousePosition.y, screenPoint.z);
curPosition =Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
var = dir = secondPos.position - scanPos;
transform.position = Math3d.ProjectPointOnLine(scanPos, dir, curPosition);
}
Your answer
Follow this Question
Related Questions
How to set Minimum and Maximum angles on Drag to Rotate Gameobject ?? 0 Answers
Get the angle of a gameObject or correct rotation 1 Answer
Limiting a GameObject Rotation 1 Answer
How to make an object appear only when I click and not when I drag 2 Answers
Move a GameObject for certain amount of time, and then move it again for a certain amount of time... 2 Answers