我在使用Raycasting时遇到了一个问题。我只想知道光标在世界空间中的位置,但只有在光标移动的情况下才行。当光标不移动时,它会跳到X轴和Z轴向下4个单位的随机点。
public class CameraMovementRay : MonoBehaviour
{
public Camera playerCam;
Ray cursorRay;
Vector3 playerPos;
public RaycastHit cursorHit;
public LayerMask clickPlain;
public bool cursorHittingFloor;
// Update is called once per frame
void Update()
{
cursorRay = playerCam.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(cursorRay, out cursorHit, 100f, clickPlain))
{
print(cursorHit.point);
Debug.DrawLine(cursorRay.origin, cursorHit.point, Color.red);
cursorHittingFloor = true;
}
else
{
Debug.LogError("Not on the grund");
cursorHittingFloor = false;
}
}
这是不可能的,但我确实找到了一些代码,可以做到这一点
``public class LookAtMouse : MonoBehaviour{。
public Camera playerCamera;
Plane movementPlane = new Plane(Vector3.up, 0f);
Vector3 lookPoint;
Ray CursorRay;
// Update is called once per frame
void Update()
{
CursorRay = playerCamera.ScreenPointToRay(Input.mousePosition);
float enter = 0.0f;
movementPlane.Raycast(CursorRay, out enter);
lookPoint = CursorRay.GetPoint(enter);
print(lookPoint);
Debug.DrawLine(CursorRay.origin, lookPoint);
transform.LookAt(lookPoint);
}
}``
你有没有试过用Camera.ScreenToWorldPoint代替Camera.ScreenPointToRay? 我认为它可能更适合你的目的,因为它以像素为单位接收一个Vector2(MousePosition),并将其方便地转换为世界空间点。我所提到的Unity文档是。https:/docs.unity3d.comScriptReferenceCamera.ScreenToWorldPoint.html。
让我知道它是如何工作的