Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/unity3d/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 当相机在UNITY3D的X轴上旋转30度时,如何使精灵跟随鼠标位置?_C#_Unity3d - Fatal编程技术网

C# 当相机在UNITY3D的X轴上旋转30度时,如何使精灵跟随鼠标位置?

C# 当相机在UNITY3D的X轴上旋转30度时,如何使精灵跟随鼠标位置?,c#,unity3d,C#,Unity3d,我试着让一个精灵跟随我的鼠标位置,我的相机在x轴上旋转30度,如果相机的旋转角度为0,0,0,但不是30,0,0,这很好,我该如何计算呢?我尝试将减法移到x位置,但没有成功,以下是我的代码: 这是附加在我想跟随鼠标的对象上的 private void FixedUpdate() { Vector3 pos = cam.ScreenToWorldPoint(Input.mousePosition); transform.position = new Vector3(pos.x, p

我试着让一个精灵跟随我的鼠标位置,我的相机在x轴上旋转30度,如果相机的旋转角度为0,0,0,但不是30,0,0,这很好,我该如何计算呢?我尝试将减法移到x位置,但没有成功,以下是我的代码:

这是附加在我想跟随鼠标的对象上的

private void FixedUpdate()
{
    Vector3 pos = cam.ScreenToWorldPoint(Input.mousePosition);
    transform.position = new Vector3(pos.x, pos.y, transform.position.z);
}

编辑:另外,我的相机不是透视图,透视图在这里不太合适,因为你还不知道精灵离相机的正确距离。取而代之的是,考虑使用RaySCAP(代数,使用<代码>平面/代码>)来计算放置精灵的位置。

在精灵的位置创建XY平面:

Plane spritePlane = new Plane(Vector3.forward, transform.position);
使用以下命令从光标位置创建光线:

找到光线与平面相交的位置并将精灵放在那里:

float rayDist;
spritePlane.Raycast(cursorRay, out rayDist);
transform.position = cursorRay.GetPoint(rayDist);
总共:

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

你应该考虑不要把它放在<代码> FixEddate 中,但是无论是<代码> Update < /Cord>还是<代码> LutupDedate <代码>(如果相机可以移动),但是如果我的相机是OrtoGrice,我还必须使用RayCask吗?因为我的相机是Z上的,而不是X上的,所以我不能计算精灵的距离吗,Y@Sociopath如果您试图问“是否使用
Raycast
效率低下?”,答案是否定的,因为
Plane.Raycast
。你可以自己实现它,但当
Plane.Raycast
已经存在时,这并不是真正必要的。谢谢我学到了很多,而且你的代码工作起来很有魅力,顺便说一句,在ScreenPointToRay上展示它的cam.ScreenPointToRay(主摄像头)
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);
}