2

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.

barkin
  • 179
  • 2
  • 12

2 Answers2

1

I hope I understood your problem.
What you can do is to store the last point as a variable and use this to draw the next line.

public class test: MonoBehaviour {

public Rigidbody rb;
public Vector3 lastPoint;

void Start () {
    rb = GetComponent<Rigidbody>();
}

void Update () {
    if (Input.GetKey(KeyCode.Mouse0))
    {
        Vector3 vect3 = new Vector3 (Input.mousePosition.x, Input.mousePosition.y, 0); 
        vect3 = Camera.main.ScreenToWorldPoint(vect3);
        //I made the vector's Z value 0 because the object's Z coordinate is also 0. 
        //This is to capture location in 2D space instead of 3D. This might be the problem. 
        if(lastPoint == null) {
             lastPoint = vect3,
             return;
        }
        Debug.DrawLine(lastPoint, vect3, Color.red, 1);
        lastPoint = vect3;
    }
}
Sebastian Kilb
  • 286
  • 1
  • 9
  • The result is still the same. Line is drawn from object to the camera. I think the problem might be ScreenToWorldPoint method, but I don't know what else I can put in its place. – barkin Jun 11 '18 at 14:23
0

Input.mouseposition gives a position in screenspace (pixels). You need to use ScreenToWorldPoint to get the mouse position relative to the camera viewing it Here is the doc necessary: https://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html

EDIT: misread your question. For some weird reason i can't delete my answer so ignore it please.