Moving a BoxCollider2D mess up Raycast2D


simple setup: A background sprite with a attached BoxCollider2D and a Rigidbody with disabled gravity. You can move the sprite by touch / mouse input. The code for that in the Update function:

newPosition = new Vector3 (transform.position.x + delta, transform.position.y, transform.position.y);
transform.position = newPosition;	

Above the sprite is another sprite (other sorting layer). If the player touched this sprite the app will load another scene. No movement.

I use a Raycast2D on a script attached to the main camera to check for touch / mouse input and forward it to the responding game object. The code for that:

Ray ray = cam.ScreenPointToRay(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, 
                              Mathf.Infinity, mask);

if (hit.collider != null) {
    // Send message, etc

Everything works fine until the user moved the first sprite. After that the ray cast only find the scrolling sprite despite the second sprite is on the top and in another layer. Do you know what’s wrong with my code?


I bet it’s because the first sprite has a rigidbody. You can set it’s position all you want but physics is only going to set it back for it’s own calculations (your raycast for example).

My favorite way to move rigidbodies is to calculate the velocity with Vector3.SmoothDamp towards the click point.