This is a mobile optimized page that loads fast, if you want to load the real page, click this text.

Проблема Что не так с клавишей E, когда я снова сажусь и читаю?

arakeli_bacunc

Участник портала
24 Июн 2025
23
6
5
Как написать функцию для входа на сервер? Например, я написал функцию для фракций, но она была неправильной. Когда я нажимаю клавишу E, она работает, но когда я выхожу, я больше не могу ничего сделать с клавишей E. Посмотрите мой отредактированный. код
Я его менял и пробовал всё.


FactionChairSystem.cs


C#:
using GTANetworkAPI;
using Omega.SDK;
using System;
using System.Collections.Generic;

namespace NeptuneEvo.OmeSystems
{
    public class FactionChairSystem : Script
    {
        private static readonly nLog Log = new nLog("FactionChairSystem");


        private static readonly Dictionary<string, ChairConfig> ChairConfigs = new Dictionary<string, ChairConfig>
        {
            {
                "Police", new ChairConfig
                {
                    Position = new Vector3(425.13043f, -979.552f, 30.71194f),
                    AnimationDict = "prop_human_seat_chair_mp_player",
                    AnimationName = "base",
                    RequiredFaction = ""
                }
            },
            {
                "EMS", new ChairConfig
                {
                    Position = new Vector3(317.4461f, -575.31287f, 43.74682f),
                    AnimationDict = "anim@amb@nightclub@peds@",
                    AnimationName = "rcmme_amanda_idle_a",
                    RequiredFaction = ""
                }
            },
            {
                "Mafia", new ChairConfig
                {
                    Position = new Vector3(-1372.817f, -466.8683f, 14.28166f),
                    AnimationDict = "anim@amb@nightclub@peds@",
                    AnimationName = "rcmme_amanda_idle_a",
                    RequiredFaction = ""
                }
            }
        };

        private class ChairConfig
        {
            public Vector3 Position { get; set; }
            public string AnimationDict { get; set; }
            public string AnimationName { get; set; }
            public string RequiredFaction { get; set; }
        }

        private static readonly Dictionary<Player, string> SittingPlayers = new Dictionary<Player, string>();

        public FactionChairSystem()
        {
            Log.Write("Инициализация FactionChairSystem с E клавишей...");
            foreach (var config in ChairConfigs)
            {
                Vector3 position = config.Value.Position;
                ColShape chairShape = NAPI.ColShape.CreateCylinderColShape(position, 2.5f, 3.0f);
                chairShape.SetData("Faction", config.Key);
                chairShape.SetData("Config", config.Value);
                Log.Write($"Создан ColShape для {config.Key} на {position.ToString()} с радиусом 2.5f и высотой 3.0f");

                chairShape.OnEntityEnterColShape += (shape, player) =>
                {
                    if (player == null || !player.Exists) return;
                    string factionName = shape.GetData<string>("Faction");
                    Log.Write($"Игрок {player.Name} вошел в зону стула {factionName} на {player.Position.ToString()}");
                    NAPI.ClientEvent.TriggerClientEvent(player, "showChairPrompt", factionName, true);
                };

                chairShape.OnEntityExitColShape += (shape, player) =>
                {
                    if (player == null || !player.Exists) return;
                    string factionName = shape.GetData<string>("Faction");
                    Log.Write($"Игрок {player.Name} вышел из зоны стула {factionName} на {player.Position.ToString()}");
                    NAPI.ClientEvent.TriggerClientEvent(player, "showChairPrompt", factionName, false);
                    NAPI.ClientEvent.TriggerClientEvent(player, "forceUnbindChairKey");
                };
            }
            Log.Write("FactionChairSystem успешно инициализирован.");
        }

        [RemoteEvent("interactWithChair")]
        public void InteractWithChair(Player player, string faction, string action)
        {
            try
            {
                if (player == null || !player.Exists) return;

                ChairConfig config = ChairConfigs[faction];
                if (action == "sit")
                {
                    if (SittingPlayers.ContainsKey(player))
                    {
                        NAPI.Chat.SendChatMessageToPlayer(player, "Вы уже сидите на стуле!");
                        return;
                    }

                    if (player.IsInVehicle)
                    {
                        NAPI.Chat.SendChatMessageToPlayer(player, "Вы не можете сесть на стул из машины!");
                        return;
                    }

                    player.Position = config.Position;
                    NAPI.Player.PlayPlayerAnimation(player, 0, config.AnimationDict, config.AnimationName, 1.0f);
                    NAPI.Chat.SendChatMessageToPlayer(player, $"Вы сели на стул {faction}.");
                    Log.Write($"Игрок {player.Name} сел на стул {faction} на {player.Position.ToString()}");
                    SittingPlayers[player] = faction;
                }
                else if (action == "stand")
                {
                    if (!SittingPlayers.ContainsKey(player))
                    {
                        NAPI.Chat.SendChatMessageToPlayer(player, "Вы не сидите на стуле!");
                        return;
                    }

                    NAPI.Player.StopPlayerAnimation(player);
                    player.Position = config.Position + new Vector3(0, 0, 0.1f);
                    NAPI.Chat.SendChatMessageToPlayer(player, $"Вы встали со стула {faction}.");
                    Log.Write($"Игрок {player.Name} встал со стула {faction} на {player.Position.ToString()}");
                    SittingPlayers.Remove(player);
                }
            }
            catch (Exception e)
            {
                Log.Write($"Ошибка InteractWithChair для {player?.Name}: {e.ToString()}");
                if (player != null && player.Exists)
                    NAPI.Chat.SendChatMessageToPlayer(player, "Произошла ошибка. Обратитесь к админу.");
            }
        }
    }
}



client.js


JavaScript:
let isChairKeyBound = false;
let currentFaction = null;

mp.events.add("showChairPrompt", (faction, show) => {
    if (show) {
        currentFaction = faction;
        mp.game.graphics.notify(`~g~Нажмите ~INPUT_CONTEXT~ (E) чтобы сесть на стул (${faction})`);
        if (!isChairKeyBound) {
            mp.keys.bind(0x45, true, function () {
                mp.events.callRemote("interactWithChair", currentFaction, isPlayerSitting() ? "stand" : "sit");
            });
            isChairKeyBound = true;
        }
    } else {
        if (isChairKeyBound) {
            mp.keys.unbind(0x45, true);
            isChairKeyBound = false;
            mp.game.graphics.notify("~w~Клавиша E освобождена.");
            currentFaction = null;
        }
    }
});

function isPlayerSitting() {
    return mp.players.local.isPlayingAnim("prop_human_seat_chair_mp_player", "base", 3, 0) || // taskFlag = 0
           mp.players.local.isPlayingAnim("timetable@reunited@ig_2", "base_idle", 3, 0) || // taskFlag = 0
           mp.players.local.isPlayingAnim("anim@amb@nightclub@peds@", "rcmme_amanda_idle_a", 3, 0); // taskFlag = 0
}

mp.events.add("forceUnbindChairKey", () => {
    if (isChairKeyBound) {
        mp.keys.unbind(0x45, true);
        isChairKeyBound = false;
        mp.game.graphics.notify("~w~Клавиша E освобождена для других действий.");
    }
});

mp.events.add("playerLeaveColshape", (shape) => {
    if (shape && shape.getVariable("Faction")) {
        mp.events.call("showChairPrompt", shape.getVariable("Faction"), false);
    }
});
 

Jerry (ChatGPT)

AI-powered language model
VIP
helper
17 Окт 2023
2,540
247
100
По вашему коду, когда игрок покидает зону стула, происходит вызов метода forceUnbindChairKey, который принудительно отменяет привязку клавиши E к действию. Возможно, проблема в этом месте. Рекомендую проверить, что после вызова forceUnbindChairKey клавиша E правильно привязывается обратно при необходимости.
 
Реакции: Inoi

Inoi

/dev/null
Команда форума
Moderator
VIP
15 Окт 2020
4,313
2,118
208
35
это вроде похоже на правильный ответ
нахуя тебе вообще unbind ?
 

Vermilion

Высший разум
High developer
BackEnd developer
FrontEnd developer
29 Сен 2021
1,479
880
181
34
Тебе нужно вынести mp.keys.bind из mp.events.add на уровень выше, что бы бинд был при инициализации клиента, а не внутри ивента.
 
Реакции: arakeli_bacunc

arakeli_bacunc

Участник портала
24 Июн 2025
23
6
5
showcairprompt) вызывается только тогда, когда игрок входит в colshape. Если событие не срабатывает или отключение мешает, E не работает. Я все понял, большое вам спасибо, все сработало, я изменил код на стороне клиента, и все сработало, большое вам спасибо


CSS:
let isInChairZone = false;
let currentFaction = null;

mp.keys.bind(0x45, true, function () {
    if (isInChairZone && currentFaction) {
        mp.events.callRemote("interactWithChair", currentFaction, isPlayerSitting() ? "stand" : "sit");
        mp.game.graphics.notify(`~y~Действие выполнено для стула ${currentFaction}.`);
    }
});

mp.events.add("showChairPrompt", (faction, show) => {
    if (show) {
        isInChairZone = true;
        currentFaction = faction;
        mp.game.graphics.notify(`~g~Нажмите ~INPUT_CONTEXT~ (E) чтобы сесть на стул (${faction})`);
        mp.game.graphics.notify("[DEBUG] Вошел в зону, E активен.");
    } else {
        isInChairZone = false;
        currentFaction = null;
        mp.game.graphics.notify("~w~Клавиша E освобождена.");
        mp.game.graphics.notify("[DEBUG] Вышел из зоны, E выключен.");
    }
});

// Проверка, сидит ли игрок
function isPlayerSitting() {
    return mp.players.local.isPlayingAnim("prop_human_seat_chair_mp_player", "base", 3, 0) ||
           mp.players.local.isPlayingAnim("anim@amb@nightclub@peds@", "rcmme_amanda_idle_a", 3, 0) ||
           mp.players.local.isPlayingAnim("timetable@reunited@ig_2", "base_idle", 3, 0);
}

// Обработка выхода из колшейпа
mp.events.add("playerLeaveColshape", (shape) => {
    if (shape && shape.getVariable("Faction")) {
        mp.events.call("showChairPrompt", shape.getVariable("Faction"), false);
    }
});
 

UchihaMadara

Гений
FrontEnd developer
27 Окт 2020
931
336
141
это вроде похоже на правильный ответ
нахуя тебе вообще unbind ?
Ну вы даете)))))



Друг, тебе нужно указывать одну и ту же функцию при mp.keys.bind и mp.keys.unbind
JavaScript:
mp.events.add("showChairPrompt", (faction, show) => {
    if (show) {
        currentFaction = faction;
        mp.game.graphics.notify(`~g~Нажмите ~INPUT_CONTEXT~ (E) чтобы сесть на стул (${faction})`);
        if (!isChairKeyBound) {
            mp.keys.bind( 0x45, true, onPressE );
            isChairKeyBound = true;
        }
    } else {
        if (isChairKeyBound) {
            mp.keys.unbind( 0x45, true, onPressE );
            isChairKeyBound = false;
            mp.game.graphics.notify("~w~Клавиша E освобождена.");
            currentFaction = null;
        }
    }
});

function onPressE()
{
    mp.events.callRemote("interactWithChair", currentFaction, isPlayerSitting() ? "stand" : "sit");
}

Если ты в mp.keys.unbind НЕ указываешь никакую функцию, то удаляется все бинды, что были сделаны на эту кнопку до этого. Абсолютно все!