- Home /
ScreenToWorldPoint has some sort of offset
Ive been trying to get this working for a while but i just cant figure it out. I have an object in my scene that has a script attached to it that raycast from its position to the mouse position. however if i move the object from its initail position the raycast seems to have an offset of some sort. (Images Below)
Script (Attached to Cube) Here:
var AttachedCamera:Camera;
function Start () {
}
function Update ()
{
var MousePosition = this.AttachedCamera.ScreenToWorldPoint(Vector3(Input.mousePosition.x,Input.mousePosition.y,15));
var hit:RaycastHit;
if (Physics.Raycast (transform.position, MousePosition,hit, 20))
{
Debug.DrawLine(this.transform.position, hit.point, Color.red);
Debug.Log(hit.point.x+","+hit.point.y);
}
Debug.DrawLine(this.transform.position, MousePosition, Color.blue);
}
How do i get rid of this offset? thanks in advace
Not sure I get the purpose of raycasting from box to camera...
$$anonymous$$aybe you would rather want to cast the opposite direction e.g. using http://unity3d.com/support/documentation/ScriptReference/Camera.ScreenPointToRay.html or http://unity3d.com/support/documentation/ScriptReference/Camera.ViewportPointToRay.html ?
I think I get your setup now ... 3 objects: - cube sending out ray (you want to check if ray hits plane) - plane above cube (can be hit by ray, if user point correctly) - camera - viewpoint of user and the place to get mouse position transformed into world from
If it is your idea that the ray from cube to plane is like pointing a canon... then rotate the ray around the cube using inputs.
If it is your idea that the ray from cube to plane needs to be visualized when you click at plane.... then you ray cast from camera to plane ins$$anonymous$$d. If it hits, you draw the line from cube to plane hitpoint.
Hope it makes sense.
Answer by Berenger · Apr 25, 2012 at 07:47 PM
The second parameter of that overload of Raycast is a direction, not a position. If transform.position is (0,0,0), it might trick you in believing it works. Try :
if( Physics.Raycast(transform.position, MousePosition - transform.position, hit, 20) )
Ahh thanks, this helped me as well. (can't upvote for some reason)