Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get sprite following mouse position when camera is rotated 30 degree on X axys on UNITY3D?

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

like image 706
Sociopath Avatar asked Dec 19 '25 22:12

Sociopath


1 Answers

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);
}
like image 84
Ruzihm Avatar answered Dec 21 '25 12:12

Ruzihm