Question by
joshlee · Mar 24, 2018 at 02:18 PM ·
unity 5cameraraycastmouseposition
How do I draw a raycast with my mouse position that is relative to the main camera?
I'm trying to learn raycasting and have the following code.
Vector3 mousePos = Camera.main.ScreenToViewportPoint(Input.mousePosition);
Vector2 targetDirection = new Vector2(mousePos.x, mousePos.y);
RaycastHit2D hit = Physics2D.Raycast(transform.position, targetDirection, rayLength);
Debug.DrawRay(transform.position, targetDirection, Color.green);
I think the problem is I don't know how to adjust my mousePos variable to be relative to my camera.
Comment
Your answer
Follow this Question
Related Questions
ScreenPointToRay generate wrong ray because camera have a parent with transform 0 Answers
Unity 5 - My raycast is hitting my player, and I can't figure out why 2 Answers
Mouse position from new InputSystem is not correct and is not the same as Input.mousePosition 0 Answers
How to tell if a looked at object has a text mesh. 0 Answers