libgdx table-layout输入事件过度触发

时间:2014-11-06 23:58:16

标签: libgdx

我正在尝试添加当用户将鼠标光标悬停在按钮上时播放的声音。问题是如果按钮内有东西,声音会播放两次:一次是光标进入按钮,一次是进入(或退出)按钮内部的东西。当光标从外部而不是从内部进入按钮时,是否有某些方法可以使输入事件触发?

示例代码:

package com.mygdx.game;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Button;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;

public class MyGdxGame extends ApplicationAdapter {
    TextureAtlas atlas;
    Skin skin;
    Image img;
    Sound enterSound;
    Stage stage;
    Table table;
    Button button;

    public void create () {
        atlas = new TextureAtlas("ui.pack");
        skin = new Skin(Gdx.files.internal("skin.json"), atlas);
        img = new Image(new Texture("badlogic.jpg"));
        enterSound = Gdx.audio.newSound(Gdx.files.internal("sound.wav"));

        stage = new Stage();
        table = new Table(skin);
        table.setFillParent(true);
        stage.addActor(table);

        button = new Button(skin);
        button.addListener(new InputListener() {
            @Override
            public void enter(InputEvent event, float x, float y, int pointer, Actor fromActor) {
                enterSound.play();
            }
        });
        button.add(img).size(64);
        table.add(button).size(128);

        Gdx.input.setInputProcessor(stage);
    }

    @Override
    public void render () {
        Gdx.gl.glClearColor(1, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        stage.act(Gdx.graphics.getDeltaTime());
        stage.draw();
    }
}

1 个答案:

答案 0 :(得分:0)

我发现包含鼠标输入元素的单元格存在类似问题。事件鼠标输入已触发3次(父单元格上有2次,最后是单元格)。

你可以这样伎俩:

// update in listener
button.addListener(new InputListener() {

            final Button thisButton = button;

            @Override
            public void enter(InputEvent event, float x, float y, int pointer, Actor fromActor) {
            if (currentMouseOveredButton == null || !currentMouseOveredButton.equals(thisButton)){  
                // mark button has made sound
                currentMouseOveredButton= thisButton;
                enterSound.play();
            }
        });

// somewhere in ui class
Button currentMouseOveredButton;