I am making a 2D Game with sprites on the new Unity3D 4.3
The linecast methord is not returning true even-though colliders are available between the points.
void Update () {
Vector3 mousePos = new Vector3 (Input.mousePosition.x, Input.mousePosition.y, -10);
Vector3 backEnd = new Vector3 (Input.mousePosition.x, Input.mousePosition.y, 10);
Debug.Log (mousePos+" "+backEnd);
if (Physics.Linecast(mousePos,backEnd)){
Debug.Log ("Hit");
}
}
Any help?
2 Answers
2
You need to convert your positions into world coordinates before making the cast. The ‘z’ coordinate is the distance in front of the camera, so your code will be something like:
Vector3 mousePos = new Vector3 (Input.mousePosition.x, Input.mousePosition.y, Camera.main.nearClipPlane);
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
Vector3 backEnd = new Vector3 (Input.mousePosition.x, Input.mousePosition.y, 20);
backEnd = Camera.main.ScreenToWorldPoint(backEnd);
Debug.Log (mousePos+" "+backEnd);
if (Physics.Linecast(mousePos,backEnd)){
Debug.Log ("Hit");
}
Note it would be simpler to use a Raycast and just set the distance of the cast to 20. Also this will not work with a 2D collider. You must have a 3D collider on the object or on a child object.
Another option is to use Physics2D.Raycast, it will work with 2D colliders.
What should i do to make it work with a Polygon Collider 2D? Can i use a 3D collider on a 2D sprite. Forgiv me if its a stupid question.I am just learning unity
– bsbimalboseIt's not a stupid question, and it is new territory since the Unity 2D stuff is new. You cannot add a 3D collider and a 2D collider to the same game object. One solution is to add a 3D collider (such as a box collider) to a child empty game object of the 2D object. You will need to size the collider appropriately for your 2D object. Given what I think you are doing, another solution is to use [OnMouseDown()][1]. OnMouseDown() works with both 3D and 2D colliders. [1]: http://docs.unity3d.com/Documentation/ScriptReference/MonoBehaviour.OnMouseDown.html
– robertbuThanks a lot, I added 3D colliders as children and it works fine
– bsbimalbose