最近在做一个小游戏的时候,遇到一个问题,就是Unity3d游戏引擎如何控制鼠标移动,以下分享一个整蛊案例,理清一种方法。
1:思路原理理清
(windows系统中可用)该方法使用System.Runtime.InteropServices该库user32.dll中的SetCursorPos函数,改变鼠标光标的坐标位置,该坐标的坐标单位为屏幕像素,如果需要变成游戏世界坐标,还需要转换一下。(如:将游戏世界坐标转成屏幕坐标,再把屏幕坐标设置进SetCursorPos函数中,进而改变鼠标光标位置)
实现步骤:
1.1导入相关库
using System.Runtime.InteropServices;
1.2设置SetCursorPos函数
//以下方法坐标单位为int类型
[DllImport("user32.dll")]
public static extern int SetCursorPos(int x, int y); //固定写法格式
public void SetTest() //自定义SetTest函数中调用SetCursorPos函数
{
int x = Random.Range(10, 600);
int y = Random.Range(10, 600);
SetCursorPos(x, y);
}
//以下方法坐标单位为float类型
/*
[DllImport("user32.dll")]
public static extern float SetCursorPos(float x, float y); //固定写法格式
public void SetTest() //自定义SetTest函数中调用SetCursorPos函数
{
int float = Random.Range(10, 600);
int float = Random.Range(10, 600);
SetCursorPos(x, y);
}
*/
2:整蛊案例
2.1游戏思路逻辑
游戏开始——鼠标光标乱动,干扰用户正常使用——按Esc键,干扰取消——按P键,干扰继续
2.2代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;
public class MoveTest : MonoBehaviour
{
bool IsWorking = true; //该布尔类型变量判断是否继续干扰
void Start()
{
IsWorking = true; //游戏开始,默认是
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
IsWorking = false; //按Esc键,取消干扰
}
if (Input.GetKeyDown(KeyCode.P))
{
IsWorking = true; //按P键,干扰继续
}
if (IsWorking==true)
{
SetTest();
}
}
[DllImport("user32.dll")]
public static extern int SetCursorPos(int x, int y);
public void SetTest()
{
int x = Random.Range(10, 600); //鼠标x坐标为随机数
int y = Random.Range(10, 600); //鼠标y坐标为随机数
SetCursorPos(x, y);
}
}
注意:以上的MoveTest.cs脚本文件,需要与游戏场景中的物体绑定