- Home /
Pixel perfect and raycasting
I'm currently working on a pixel perfect point and click game. I've managed to make it pixel perfect, or at least close enough, by using a render texture rendered at 320x200, which is placed in front of another camera that renders at a higher resolution based on scaling (x2, x3, etc).
Unfortunately, that means I can't use OnMouseDown. I've tried using Raycasts, but the 320x200 camera is of course much smaller, causing the rays to only work in the lower right corner. Also, I tried casting a ray from the render camera onto the render texture and cast a ray from the lowres camera using the texture coordinates, but I can't get the 2D raycast to work from the lowres camera.
Sorry if it's a bit confusing as I typed this quite late and I was a bit confused then.
This is the code I have thus far (added to the main render camera)
public class CameraRaycast : MonoBehaviour
{
public Camera nativeCamera;
// Use this for initialization
void Update()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit2D renderHit = Physics2D.Raycast(Input.mousePosition, Vector3.forward);
Debug.DrawRay(Input.mousePosition, Input.mousePosition - GetComponent<Camera>().ScreenToWorldPoint(Input.mousePosition), Color.red);
if (renderHit.collider != null)
{
Debug.Log("First ray hit " + renderHit.transform.gameObject.name);
}
}
}
}
Well, I solved it. The Vector2 origin of the Raycast2D is now
GetComponent<Camera>().ScreenToWorldPoint(Input.mousePosition)
The script is added to the main camera (the one that renders the quad with the render texture) and no matter what resolution the game renders to, the raycast always finds the colliders.
I do have to align both cameras together so the raycast from the render camera actually finds the collider at the same coordinates as they are on the screen. I do this in the Start function so the render camera can be placed somewhere else to leave the sprites in the editor viewport unobstructed.
Your answer