Figuring out where you clicked on a sprite/Collider2D

Hi there,

First post on the Unity-forums - and I’m just trying to figure it all out… This one I couldn’t find anything about - so hopefully you guys can help me.

I have a sprite falling from the sky - when i click it I want it to bounce depending on where I clicked it. Clicking more left on the sprite would make it bounce back up towards the right - and vise versa.

Must admit that I’m out of ideas. I’ve found the location I click with the mouse using:

Input.mousePosition.x/.y

And the location of the sprite by using:

Vector3 pos2d = GameObject.Find("MainCamera").camera.WorldToScreenPoint(rigidbody2D.transform.position);

Using this I had hoped I could figure out in what percentage of the sprite I was clicking - but without knowing the pixel-size of the Collider2D - I don’t think I can do it that way.

I’m still trying to wrap my head around the raycast-stuff and all that, and the answer might lay there somewhere - but I’m on deep waters here :slight_smile:

Anyone who can give me a little hint (C#)?

Thanks in advance.

// Yoc.

This is my suggestion
first simply detect collision when moueclick
if you click an object, simply find the distance/direction from your position (x/y) to the center position of your object(x/y) and from that you can apply a force to be proportional to where you clicked it

this however will only work on square/circle shapes in general. If you want to have some oblong or odd shape, that’d require more work.

This would sound like the solution - could you provide me with some hints on how? :slight_smile:

// Yoc.

I think raycasting is how I’d approach it.

You can feed your mousePosition into a camera function called ScreenPointToRay. Pass that ray to a Raycast, which will get you a RaycastHit which contains the point where the ray collided with something.