I'm trying to get a sprite following my mouse position with my camera rotated at 30 on x axys, this works fine if camera have a rotation of 0,0,0 but not on 30,0,0, how I have to calculate this? I have tryed substracting to x position with no success, here is my code:
this is attached on the object I want to follow the mouse
private void FixedUpdate()
{
Vector3 pos = cam.ScreenToWorldPoint(Input.mousePosition);
transform.position = new Vector3(pos.x, pos.y, transform.position.z);
}
EDIT: also my camera is ortographic not perspective
ScreenToWorldPoint isn't really appropriate here because you don't already know the proper distance to put the sprite away from the camera. Instead, consider using a raycast (algebraically, using Plane) to figure where to put the sprite.
Create an XY plane at the sprite's position:
Plane spritePlane = new Plane(Vector3.forward, transform.position);
Create a ray from the cursor's position using Camera.ScreenPointToRay:
Ray cursorRay = cam.ScreenPointToRay(Input.mousePosition);
Find where that ray intersects the plane and put the sprite there:
float rayDist;
spritePlane.Raycast(cursorRay, out rayDist);
transform.position = cursorRay.GetPoint(rayDist);
Altogether:
private void FixedUpdate()
{
Plane spritePlane = new Plane(Vector3.forward, transform.position);
Ray cursorRay = cam.ScreenPointToRay(Input.mousePosition);
float rayDist;
spritePlane.Raycast(cursorRay, out rayDist);
transform.position = cursorRay.GetPoint(rayDist);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With