unity设置鼠标按键焦点事件

本文介绍了一个Unity中的脚本,用于在游戏中限制鼠标光标的位置,确保其不会超出屏幕边界。通过检测鼠标位置并使用SetCursorPos函数调整,实现游戏内鼠标的平滑控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;
public class Mousepause : MonoBehaviour
{
    [DllImport("user32.dll", EntryPoint = "SetCursorPos")]
    public static extern int SetCursorPos(int x, int y);
    public bool ck = false;
	// Use this for initialization
	void Start () {
       SetCursorPos(200,200);
	}
	
	// Update is called once per frame
	void Update () {
		if(!ck)
        {
            if(Input.mousePosition.x<1)
            {
                //Mathf.RoundToInt数学算法,取整
                SetCursorPos(Mathf.RoundToInt(Screen.width * 0.5f), Mathf.RoundToInt(Input.mousePosition.y));
            }
            if(Input.mousePosition.y<1)
            {
                SetCursorPos(Mathf.RoundToInt(Input.mousePosition.x), Mathf.RoundToInt(Screen.height * 0.5f));
            }
            if(Input.mousePosition.x>Screen.width-5)
            {
                SetCursorPos(Mathf.RoundToInt(Screen.width * 0.5f), Mathf.RoundToInt(Input.mousePosition.y));
            }
           
        }
	}
    private void OnApplicationFocus()
    {
    
        ck = !ck;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值