简体   繁体   中英

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

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM