I’m trying to incorporate my mouse for aiming in my 2D sidescroller. I tried to emulate the technique used in Survival Shooter tutorial for aiming.
Based on my understanding a Ray is created that goes from the Camera through the screen using Input.mousePosition, and into the scene. When that Ray hits a collider its information is sent to hit. The coordinates can be accessed using hit.point. Debug.Log() always give a zero vector though.
void Update () {
Ray camRay = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
Physics.Raycast(camRay, out hit, Mathf.Infinity);
Debug.Log("hit.point = " + hit.point);
}
You should put an if statement there. There is probably no hit and you are seeing the default values of the RaycastHit.
void Update ()
{
Ray camRay = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(camRay, out hit, Mathf.Infinity))
Debug.Log("hit.point = " + hit.point);
}
Thanks for the suggestion Garth but I think I found the issue. For some reason the code only works with Box Colliders (3D) and not with Box Collider 2D.
My current solution to this is to use create a background that uses a normal Box Collider instead, but I’m curious if anyone knows why the behavior described above is happening.
Use Physics2D rather than Physics, which is for 3D. You will probably want to switch to OverlapPoint for into the screen type behaviour in 2D as well.
Ya just to clarify, Unity uses PhysX for their 3D physics and Box2D for their 2D physics. These do not interact with each other.
Stuff in Box2D land won’t affect PhysX stuff and vise versa.