【发布时间】:2022-01-28 12:36:22
【问题描述】:
我想用类似的方式移动鼠标指针:mouseposition += new Vector2(x, y)。 “GetCursorPos”始终为 (0, 0),因此我无法使用 delta 值移动鼠标指针,但我可以使用 SetCursorPos 将其移动到某个坐标。我尝试了以下代码:
using UnityEngine;
using System.Runtime.InteropServices;
public class all : MonoBehaviour
{
public Vector2 MoveMouse;
[DllImport("user32.dll")]
public static extern bool SetCursorPos(int X, int Y);
[DllImport("user32.dll")]
public static extern bool GetCursorPos(out Vector2 pos);
private void FixedUpdate()
{
Vector2 cursorPos = new Vector2();
GetCursorPos(out cursorPos);
//finding the cursor's position
SetCursorPos(Mathf.RoundToInt(cursorPos.x + MoveMouse.x), Mathf.RoundToInt(cursorPos.y + MoveMouse.y));
//cursorpos += MoveMouse
}
}
我尝试了另一个代码,将 GetCursorPos 替换为另一个值,但是当我移动鼠标指针时它会随机移动一点。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;
public class all : MonoBehaviour
{
[DllImport("user32.dll")]
public static extern bool SetCursorPos(int X, int Y);
public Vector2 offset;
bool started;
private void Start()
{
StartCoroutine(waiting());
}
private void FixedUpdate()
{
if (started)
{
SetCursorPos(Mathf.RoundToInt(Input.mousePosition.x + offset.x), Mathf.RoundToInt(-(Input.mousePosition.y + offset.y)));
}
}
IEnumerator waiting()
{
Application.runInBackground = true;
SetCursorPos(0, 0);
yield return new WaitForEndOfFrame();
offset = new Vector2(-Input.mousePosition.x, -Input.mousePosition.y);
started = true;
}
}
【问题讨论】:
-
这个答案说得很好:stackoverflow.com/a/46999239/13460353我希望这会有所帮助。
-
我想要鼠标在windows坐标系中的位置,或者平移鼠标。该答案使用 input.mouseposition 和 screentoworldpoint,这两件事是不同的
标签: c# visual-studio unity3d mouse