首页 > 解决方案 > C++ SFML 操纵杆输入

问题描述

我正在使用 SFML 和 C++ 进行大学结对编程项目,以制作两人 2D 游戏。


TL;博士:

如何让Xbox360Controller游戏中的任何地方都可以访问实例?[请记住,如果您建议Singleton Pattern将连接两个控制器]。


我们有一个从大学课程中编写的引擎,我们制作了诸如ResourceManager, SceneGraph, CommandQueue, StateStack,Input Action bindings等之类的东西。

引擎功能分为update(),draw()handleEvent()单独handleRealtimeInput()Player.cpp.

我在我的Github中编写并重新编写了一个Xbox360Controller类(暂时忽略方法)。static GetController()

最初,dustinfreeman 的 GitHub中的原始类使用了一种Singleton模式,但我们需要允许连接 2 个控制器。

我不确定我是否应该仍然使用 Singleton 类型的类,还是应该Xbox360Controller为特定玩家创建一个实例。

目前,我正在尝试使用第二个实现,但是Application.cpp当我在构造函数中创建实例时,我希望整个应用程序访问控制器事件,如下所示:

Application::Application()
    :mWindow(sf::VideoMode(1024, 768), "Audio", sf::Style::Close)
    , mTextures()
    , mFonts()
    , mPlayer()
    , mMusic()
    , mSounds()
    , mStateStack(State::Context(mWindow, mTextures, mFonts, mPlayer, mMusic, mSounds))
    , mStatisticsText()
    , mStatisticsUpdateTime()
    , mStatisticsNumFrames(0)
{
    mWindow.setKeyRepeatEnabled(false);

    mFonts.load(FontIDs::Main, "Media/Sansation.ttf");

    mTextures.load(TextureIDs::TitleScreen, "Media/Textures/TitleScreen.png");
    mTextures.load(TextureIDs::Buttons, "Media/Textures/Buttons.png");

    registerStates();
    mStateStack.pushState(StateIDs::Title);

    // This line creates an instance for a controller if a controller is connected
    if (sf::Joystick::Count > 0)
    {
        std::cout << "Joystick Connected." << std::endl;
        // This instance should be available everywhere
        Xbox360Controller controller(0);
    }
}

// This runs in the game-loop
void Application::processInput()
{
    sf::Event event;
    while (mWindow.pollEvent(event))
    {
        if (sf::Joystick::isConnected(0))
        {
            // Do something [For testing], eventually, pass the event into StateStack
        }

        mStateStack.handleEvent(event);

        if (event.type == sf::Event::Closed)
        {
            mWindow.close();
        }
    }
}

圣诞快乐。

标签: c++sfmljoystick

解决方案


推荐阅读