How to use raycast in screen space camera
Hello everyone,
I use raycasts like this:
hit = Physics2D.Raycast(Input.mousePosition, Cible, 10f,9); hitsX = Physics2D.RaycastAll(Input.mousePosition, Vector3.right, 600); hitsY = Physics2D.RaycastAll(Input.mousePosition, Vector3.right, 600);
and it's work very well. But now i changed my canvas for Screen Space camera and it's doesn'work anymore. Only this kind of raycast works but i don't need this:
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out raycastHit))
{
Debug.Log(raycastHit.collider.gameObject.name);
}
Can you help me?
Thank you.
Answer by bsivy · Dec 08, 2020 at 02:11 PM
I had a similar issue when switching from screen space - overlay
to screen space - camera
. Not the same code but this is how I solved it:
// Vector3 position = Input.mousePosition;
if (_canvas.renderMode == RenderMode.ScreenSpaceCamera)
{
position = cam.WorldToScreenPoint(position);
}
_pointerEventData = new PointerEventData(_eventSystem) { position = position };
List<RaycastResult> results = new List<RaycastResult>();
_raycaster.Raycast(_pointerEventData, results);
Amazing, thanks. Just adding WorldToScreenPoint solved my problem.
What position do you give to WorldToScreenPoint (Mouse position is not in world coordinate) ? What is _raycaster here ? What is doing the PointerEventData ?
Your answer
Follow this Question
Related Questions
Three out of four of these raycasts aren't working 0 Answers
2D How to reflect a raycast with a line renderer 0 Answers
RaycastHit2D ground detection 1 Answer
I think my raycast detects destroyed gameobjects 0 Answers
How do I Implement Linecast2d 0 Answers