- Home /
Mouse drag gameobject
Hi! I have created a script for dragging my gameobjects with the mouse. The problem is that when the gameobject's z-axis changes the gameobject is not behind the mousecursor. It still moves when the mousecursor changes position, but it is displaced compared to the mousecursor.
How do I make it work so the gameobject always stay behind the mousecursor even when the gameobject's z-axis changes.
My code so far:
function OnMouseDown() {
clicked = true;
renderer.material.color = Color.blue;
screenPoint = Camera.mainCamera.WorldToScreenPoint(myTransform.position);
offset = myTransform.position - Camera.main.ScreenToWorldPoint(
new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}
function OnMouseDrag() {
var curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
var curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
myTransform.position = curPosition;
if (myTransform.position.y > 2.1) {
myTransform.position.z = 0;
screenPoint = Camera.mainCamera.WorldToScreenPoint(myTransform.position);
offset = myTransform.position - Camera.main.ScreenToWorldPoint(
new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
} else {
myTransform.position.z = -4;
myTransform.localScale.x = 0.5;
myTransform.localScale.y = 0.5;
screenPoint = Camera.mainCamera.WorldToScreenPoint(myTransform.position);
offset = myTransform.position - Camera.main.ScreenToWorldPoint(
new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}
}
This may help you: http://answers.unity3d.com/questions/60486/look-at-the-mouse.html
I've had this same problem. It can be solved in several ways. But I'm not sure about some things. First, the z axis means moving away from the camera in your situation, right? Can you show us a video or pictures of this happening?
Your camera also may be set to perspective. This may be the reason that your object appears to not be behind the mouse -- because the camera's view is distorted by distance. Let me know if this was it?
S
Please convert this to a comment. Use the "more" drop down. Answers are reserved for attempted answers to a question. By putting a non-answer here, the question is marked as having an answer and is notably less likely to get an answer.
Yeah sure. I took these pictures of it (the red dot is the mouse cursor)
The first one with z-xis = 0
The second ond with z-axis -4
As robertu mentioned:
Please convert this to a comment. Use the "more" drop down. Answers are reserved for attempted answers to a question. By putting a non-answer here, the question is marked as having an answer and is notably less likely to get an answer.