Newer
Older
AlgebraicDataflowArchitectureModel / GameEngine / src / main / java / gameEngine / views / Button.java
package gameEngine.views;

import gameEngine.input.Input;
import gameEngine.input.MouseInput;

import java.util.ArrayList;
import java.util.List;

public class Button implements IUpdatable {
    private Sprite buttonSprite;
    private List<Runnable> onClickListeners = new ArrayList<>();
    private boolean isPressed = false;

    private Color normalColor = new Color(1f, 1f, 1f, 1f);
    private Color pressedColor = new Color(0.5f, 0.5f, 0.5f, 1f);

    public Button(float x, float y, Sprite sprite) {
        buttonSprite = sprite;
        buttonSprite.setPosition(x, y);
    }

    public Button(float posX, float posY, float scaleX, float scaleY){
        this(posX, posY, new Sprite(Window.resourcePath + "button.png"));
        buttonSprite.setScale(scaleX, scaleY);
    }

    public Button(){
        this(0,0, new Sprite(Window.resourcePath + "button.png"));
    }

    public void update() {
        buttonSprite.update();
        float mouseX = MouseInput.getX();
        float mouseY = MouseInput.getY();

        if (Input.GetMouseButtonDown(0) && buttonSprite.isMouseOver(mouseX, mouseY)) {
            isPressed = true;
            buttonSprite.setColor(pressedColor);
        }

        if (Input.GetMouseButtonUp(0)) {
            buttonSprite.setColor(normalColor);
            if (isPressed && buttonSprite.isMouseOver(mouseX, mouseY)) {
                for (Runnable listener : onClickListeners) {
                    listener.run();
                }
            }
            isPressed = false;
        }
    }

    public void addListener(Runnable listener) {
        onClickListeners.add(listener);
    }

    public void clearListeners() {
        onClickListeners.clear();
    }

    public void setNormalColor(Color normalColor) {
        this.normalColor = normalColor;
    }

    public void setPressedColor(Color pressedColor) {
        this.pressedColor = pressedColor;
    }

    public void setPosition(float x, float y) {
        buttonSprite.setPosition(x,y);
    }

    public void setScale(float x, float y){
        buttonSprite.setScale(x,y);
    }
}