Worker Selection - UQdeco2800/2022-studio-3 GitHub Wiki

Overview

Worker units are selected when the player hovers the mouse cursor over them and clicks with the left-mouse button. In this way, multiple worker units can be selected by left-clicking on more than one. Any worker units can be de-selected by pressing the ESC key on the keyboard.

Technical breakdown

Selecting workers

Whenever the player presses the left-mouse button, this input is handled using the WorkerInputComponent which is added to every worker. The handler used is the touchDown function which is inherited and overwritten from the InputComponent class.

The handler takes as input screenX (the x-position of the cursor), screenY (the y-position of the cursor) and button. The (x,y) position of the mouse in screen coordinates is converted into a world position using the screenToWorldPosition function.

If the button pressed is the left-mouse button, then we check if the world position of the mouse is within the bounds of the worker using the inEntityBounds function. If so, then the isSelected attribute within the component is toggled to true, and the worker is considered to be selected.

public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        // Find the world coordinates of the cursor
        Vector2 cursorWorldPos = screenToWorldPosition(screenX, screenY);
        if (button == Input.Buttons.RIGHT) {
            ...
        } else if (button == Input.Buttons.LEFT) {
            // Worker is not selected.
            // Determine if user is trying to select the entity.
            if (inEntityBounds(cursorWorldPos.x, cursorWorldPos.y)) {
                isSelected = true;
            }
        }
        return false;
    }

De-selecting workers

Whenever the player presses the ESC button, then the input is again handled by the WorkerInputComponent. The handler used is the keyDown function which takes as input the keyCode (numerical representation of key pressed). If the key pressed is found to be the ESC key, then isSelected is toggled to false.

public boolean keyDown(int keyCode) {
        if (keyCode == Input.Keys.ESCAPE) {
            // Deselect the worker (if not already)
            isSelected = false;
        }
        return false;
    }