将鼠标指针向特定方向统一移动

问题描述 投票:-1回答:1

我想用如下方法移动鼠标指针: mouseposition += new Vector2(x, y). "GetCursorPos "总是(0, 0),所以我不能用delta值来移动鼠标指针,但我可以用SetCursorPos把它移动到某个坐标。我尝试了下面的代码,结果发现,我的鼠标指针总是(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;
    }
}
c# visual-studio unity3d mouse
1个回答
0
投票

所以我只好自己动手了

using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;

public class MouseControl : MonoBehaviour
{
    [DllImport("user32.dll")]
    public static extern bool SetCursorPos(int X, int Y);
    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool GetCursorPos(out MousePosition lpMousePosition);

    public int xdmp;
    public int ydmp;
    [StructLayout(LayoutKind.Sequential)]
    public struct MousePosition
    {
        public int x;
        public int y;
    }
    private void FixedUpdate()
    {

        if(Input.GetKeyDown(KeyCode.Space))
        {
            xdmp = 0;
            ydmp = 0;
        }

        MousePosition mp;
        GetCursorPos(out mp);

        print(mp.x + " " + mp.y);

        SetCursorPos(mp.x + xdmp, mp.y + ydmp);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.