I started messing around with Unity like a few days ago and I'm no coding expert so pardon me if I'm missing anything obvious.
For a few hours I've been trying to draw a line from an object on the screen to anywhere I click in 2D space and failing miserably. I googled it but couldn't find a working solution. The problem is when I click, the line is drawn from the object to the position of the camera instead of the position of mouse. I don't know what to do at this point. I could use some help.
Here's the simplified version of the code.
public class test: MonoBehaviour {
public Rigidbody rb;
public Vector3 vect3;
void Start () {
rb = GetComponent<Rigidbody>();
}
void Update () {
if (Input.GetKey(KeyCode.Mouse0))
{
vect3 = new Vector3 (Input.mousePosition.x, Input.mousePosition.y, 0);
//I made the vector's Z value 0 because the object's Z coordinate is also 0.
//It is to avoid capturing 3D coordinates.
Debug.DrawLine(rb.position, Camera.main.ScreenToWorldPoint(vect3), Color.red, 1);
}
}
}
edit: Fixed a method error in code.
edit2: I solved it. Turns out the z variable of Camera.main.ScreenToWorldPoint's parameter (vect3) represents the distance from from camera and since I made its value 0, the line is drawn directly to the camera. Changing vect3's z value to transform.position.z - Camera.main.transform.position.z fixed it.