- Home /
Draw a Ray to the Mouse Postion
I'm trying to draw a ray to the mouse position from my player but it is acting very strange. Firstly the whole ray isn't even where the mouse is but if I use Debug.DrawLine instead of Debug.DrawRay then it works. Here is a screen shot of the first problem. The second problem is whenever I move the player the end point of the line also moves when it shouldn't because the mouse isn't actually moving, just the player. Here is the code:
var mouseWorldPosition;
var raycastHit : RaycastHit;
function Update(){
DestroyTile();
}
function DestroyTile(){
var mouseWorldPosition : Vector3 = Camera.main.ScreenToWorldPoint(Vector3(Input.mousePosition.x,Input.mousePosition.y, 15));
Debug.DrawRay(transform.position, mouseWorldPosition, Color.red);
}
Can someone please tell me why it's acting so strangly?
Thanks.
Answer by fherbst · Aug 15, 2011 at 06:07 PM
var mouseWorldPosition : Vector3 = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Debug.DrawLine(transform.position, mouseWorldPosition, Color.red);
Debug.DrawRay takes a direction as second parameter.
And ScreenToWorldPoint can use the mousePosition directly.
So, use Input.mousePosition directly, and not like you did (what are the 15 units in z direction thought to do?).
Ok, but that doesn't help me because I cant actually use that ray to detect if it's hitting anything. The reason for this is because one it's going from the player to the camera and I need the end point 15 units in front of the camera. And two because the ray is still above the mouse. Change drawLine to drawRay and you will see what I mean.
Why do you need the endpoint to be somewhere else? And DrawRay takes a vector and a direction (relative to the first vector), not two vectors, so you have to change the second one to (vector1 - vector2) to have it go from vector2 to vector1.
Your answer
Follow this Question
Related Questions
Call an exorcist. 1 Answer
How I can save mouse position ? 0 Answers
Can I fake the mouse/touch position relative to the real mouse/touch position? 0 Answers
Image ui point at mousse position 0 Answers