use*_*964 4 c# tooltip cursor unity-game-engine
我做了一个工具提示面板跟随光标
void Update () {
this.transform.position = Input.mousePosition;
}
Run Code Online (Sandbox Code Playgroud)
在更新功能中。
面板“滞后”,在四分之一秒后移动到光标位置,这很烦人 有没有更好的方法来做到这一点?我可以以某种方式将它“粘”到光标上吗?这是我从右向左移动鼠标时的样子。
鼠标静止时面板位于光标下方,只有在大力移动时才会减弱。
您不能Input.mousePosition;直接分配给 UI 转换。您必须使用RectTransformUtility.ScreenPointToLocalPointInRectangle将鼠标位置和 Canvas 转换为 UI 可以理解的适当位置。
之后,您使用Canvas.transform.TransformPoint(result)来获取应分配给 UI/Panel 位置的鼠标的最终位置。
这段代码应该是这样的:
public Canvas parentCanvas;
public void Start()
{
Vector2 pos;
RectTransformUtility.ScreenPointToLocalPointInRectangle(
parentCanvas.transform as RectTransform, Input.mousePosition,
parentCanvas.worldCamera,
out pos);
}
public void Update()
{
Vector2 movePos;
RectTransformUtility.ScreenPointToLocalPointInRectangle(
parentCanvas.transform as RectTransform,
Input.mousePosition, parentCanvas.worldCamera,
out movePos);
transform.position = parentCanvas.transform.TransformPoint(movePos);
}
Run Code Online (Sandbox Code Playgroud)
确保将 Canvas 分配给 parentCanvas 插槽。
编辑:
对于您问题中的原始图像,我认为您正在移动的 UI 始终位于光标的一侧。链接视频后,我才意识到问题是对象移动到光标位置时有延迟。
这是 Unity 的问题。Unity 目前正在重新设计 InputSystem 来解决这个问题。当前的解决方法是禁用光标,Cursor.visible = false;然后使用另一个带有光标图标的图像作为光标。
在线查找好的光标并将其分配给编辑器中的 mouseCursor 插槽纹理..
public Canvas parentCanvas;
public RawImage mouseCursor;
public void Start()
{
Cursor.visible = false;
}
public void Update()
{
Vector2 movePos;
RectTransformUtility.ScreenPointToLocalPointInRectangle(
parentCanvas.transform as RectTransform,
Input.mousePosition, parentCanvas.worldCamera,
out movePos);
Vector3 mousePos = parentCanvas.transform.TransformPoint(movePos);
//Set fake mouse Cursor
mouseCursor.transform.position = mousePos;
//Move the Object/Panel
transform.position = mousePos;
}
Run Code Online (Sandbox Code Playgroud)
最后,你会注意到我没有Input.mousePosition直接使用来设置 UI 位置。不要使用它。原因是当您更改 Canvas RenderMode 并分配相机时,Input.mousePosition将不起作用,但RectTransformUtility.ScreenPointToLocalPointInRectangle解决方案应该有效。