简体   繁体   English

当相机在 UNITY3D 上的 X 轴上旋转 30 度时,如何获得鼠标 position 的精灵?

[英]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?我试图在我的鼠标 position 之后获得一个精灵,我的相机在 x 轴上旋转 30,如果相机的旋转为 0,0,0 但不是 30,0,0,这工作正常,我必须如何计算这个? I have tryed substracting to x position with no success, here is my code:我尝试减去 x position 没有成功,这是我的代码:

this is attached on the object I want to follow the mouse这个附在object上 我要跟着鼠标

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. ScreenToWorldPoint在这里并不合适,因为您还不知道将精灵远离相机的适当距离。 Instead, consider using a raycast (algebraically, using Plane ) to figure where to put the sprite.相反,考虑使用光线投射(代数,使用Plane )来确定放置精灵的位置。

Create an XY plane at the sprite's position:在精灵的 position 处创建一个 XY 平面:

Plane spritePlane = new Plane(Vector3.forward, transform.position);

Create a ray from the cursor's position using Camera.ScreenPointToRay :使用Camera.ScreenPointToRay从光标的 position 创建一条射线:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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