How do i draw a line between my selected gameobject and my mouse cursor?
I'm working on some simple rts and would like to display a line between my selected unit and the mouse position with showing the actual distance . Any suggestions how to achieve that?
Answer by manipalsingh · Aug 22, 2016 at 06:05 AM
Hi, You can simply do it by using line renderer. Add line renderer to your GameObject and Set position of line renderer using script and set size of line renderer positions to 2. I'm sure you can find the distance between them. Here is a part of the code....
private LineRenderer LR;
public List<Vector2> positions;
private Renderer Rend;
Vector2 PositionOfGameObject;
void Start()
{
LR = GetComponent<LineRenderer>();
Rend = GetComponent<Renderer>();
//Set your GameObject position from where you want draw a line
PositionOfGameObject = new Vector2(0f,0f,0f);
}
void Update()
{
LR.SetPosition(0, PostionOfGameObject);
Vector2 CursorPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
LR.SetPosition(1, CursorPosition);
// set your Texture Wrap Mode to Repeat in case you want some texture to repeat over the line.
Rend.material.mainTextureScale = new Vector2((int)Vector2.Distance(PostionOfGameObject, CursorPosition, 1);
}
Answer by seanwiemken · May 19, 2021 at 02:27 AM
hello, I know this is an old post. but is this possible in a 3d environment? I am trying to do the same thing, my mouse position does not seem to update. Even though I have it in the update method.
Make sure to add z position to Input,mousePosition, otherwise it will not detect any changes e.g Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10f));