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?
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.