javascript 为什么我的Tampermonkey脚本在选中复选框时不移动播放器?

gopyfrb3  于 2023-05-27  发布在  Java
关注(0)|答案(1)|浏览(109)

我通过tampermonkey为网站制作了一个脚本,其想法是当复选框被选中时,玩家必须移动,但由于某种原因它不移动。我不知道出了什么问题。

// ==UserScript==
// @name         Erz Online Energy Pump
// @namespace    https://app.erz.online/
// @version      1
// @description  Adds a panel to the lower right corner of the screen on https://app.erz.online/ with a checkbox labeled 'pumping energy' that activates pressing the 'A' and 'D' keys to move in the game.
// @match        https://app.erz.online/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    const panel = document.createElement('div');
    panel.style.position = 'fixed';
    panel.style.bottom = '100px';
    panel.style.right = '0';
    panel.style.width = '200px';
    panel.style.height = '100px';
    panel.style.backgroundColor = '#262626';
    panel.style.borderRadius = '5px';
    panel.style.padding = '10px';
    panel.style.boxShadow = '2px 2px 5px rgba(0, 0, 0, 0.3)';
    panel.style.zIndex = '0';

    const checkbox1 = document.createElement('input');
    checkbox1.type = 'checkbox';
    checkbox1.id = 'pumping-energy';
    checkbox1.style.marginRight = '10px';

    const label1 = document.createElement('label');
    label1.htmlFor = 'pumping-energy';
    label1.style.color = "#ffffff";
    label1.innerText = 'Pumping Energy';

    panel.appendChild(checkbox1);
    panel.appendChild(label1);

    document.body.appendChild(panel);

    checkbox1.addEventListener('change', function() {
        if (this.checked) {
            console.log("on");
            var canvas = document.getElementById('unity-canvas');
            simulateKeyPress(canvas, 65);
        } else {
            console.log("off");
        }
    });

    function simulateKeyPress(canvas, keyCode) {
        var keyboardEvent = new KeyboardEvent('keydown', { keyCode: keyCode });
        console.log(keyboardEvent)
        canvas.dispatchEvent(keyboardEvent);
    }
})();

我尝试使用document.dispatchEvent(keyboardEvent);但是没有任何作用,我还尝试使用左箭头的代码

kpbpu008

kpbpu0081#

请尝试修改此部分

checkbox1.addEventListener('change', function() {
        if (this.checked) {
            console.log("on");
            var canvas = document.getElementById('unity-canvas');
            simulateKeyPress(canvas, 65);
        } else {
            console.log("off");
        }
    });

document.addEventListener('change','#pumping-energy', function() {
        if (this.checked) {
            console.log("on");
            var canvas = document.getElementById('unity-canvas');
            simulateKeyPress(canvas, 65);
        } else {
            console.log("off");
        }
    });

相关问题