Collision 2D - Mouse Object

Hi Everyone,

I’m using a mouse-controlled game object for my cursor and need it to change based on what it’s pointing at. I was able to do this in 3d no problem using colliders and triggers, but the move to 2D hasn’t worked out for this particular feature.

Here’s the code I’m working with. Movement works fine, but no message comes up when the cursor intersects with another collider. Coordinates on both objects show that they are indeed in the same place, and they’re on the same layer.

Any advice is appreciated, thanks.

public class CursorScript : MonoBehaviour

{
	public Vector2 mousePosition;
	public Vector2 wantedPosition;

	void Start () 
	{
		Debug.Log ("started");
		Screen.showCursor = false;
	}
	
	void Update () 
	{
		mousePosition = Input.mousePosition;
		wantedPosition = Camera.main.ScreenToWorldPoint (mousePosition);
		transform.position = wantedPosition;
	}

	void OnTriggerEnter2D(Collider2D otherCollider)
	{
		Debug.Log ("collided");
	}
}

You should not set position directly, it causes bad effects with Box2D. You can try using Physics2D.OverlapPointNonAlloc instead

For those finding this 8 years later. If you’re using a Collider2D setting the transfrom’s position directly via transform can cause issues. You should instead apply the movement to the RigidBody2D with something like RigidBody2D.movePosition().

Example Code (Using the New Unity Input System):

          Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Mouse.current.position.ReadValue());
          mousePosition.z = 0;
          this.gameObject.GetComponent<Rigidbody2D>().MovePosition(mousePosition);