Skip to content

Commit

Permalink
feat: added EntitySelectionRectangle, closes #720
Browse files Browse the repository at this point in the history
  • Loading branch information
AlmasB committed Jan 24, 2025
1 parent 878533a commit 5fb6e02
Showing 1 changed file with 82 additions and 0 deletions.
82 changes: 82 additions & 0 deletions fxgl/src/main/kotlin/com/almasb/fxgl/app/scene/GameScene.kt
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,16 @@ import javafx.beans.property.SimpleIntegerProperty
import javafx.beans.value.ChangeListener
import javafx.collections.ObservableList
import javafx.event.EventHandler
import javafx.geometry.Point2D
import javafx.geometry.Rectangle2D
import javafx.scene.Group
import javafx.scene.Node
import javafx.scene.SceneAntialiasing
import javafx.scene.SubScene
import javafx.scene.input.MouseEvent
import javafx.scene.paint.Color
import javafx.scene.robot.Robot
import javafx.scene.shape.Rectangle
import javafx.scene.transform.Rotate
import javafx.scene.transform.Scale
import java.util.concurrent.Callable
Expand Down Expand Up @@ -84,6 +88,10 @@ internal constructor(width: Int, height: Int,

private val updatableViews = arrayListOf<View>()

val entitySelectionRectangle: EntitySelectionRectangle by lazy {
EntitySelectionRectangle(this)
}

/**
* If set to true, Game Scene will require calling step()
* to advance each frame.
Expand Down Expand Up @@ -363,6 +371,8 @@ internal constructor(width: Int, height: Int,

timer.clear()

entitySelectionRectangle.lastSelection.clear()

viewport.unbind()
gameRoot.children.clear()
uiRoot.children.clear()
Expand Down Expand Up @@ -461,4 +471,76 @@ class GameView(val node: Node, zIndex: Int) {
set(value) {
zProperty.value = value
}
}

class EntitySelectionRectangle(
private val gameScene: GameScene
) : Rectangle(), View {

private val world = gameScene.gameWorld
private val input = gameScene.input

/**
* This list is populated on [stopSelection].
*/
val lastSelection: MutableList<Entity> = arrayListOf()

private var selectionStart: Point2D = Point2D.ZERO

init {
fill = Color.web("darkblue", 0.4)
stroke = Color.LIGHTBLUE
isVisible = false
}

fun startSelection() {
if (scene == null) {
gameScene.addUINode(this)
}

selectionStart = input.mousePositionUI
translateX = selectionStart.x
translateY = selectionStart.y
width = 0.0
height = 0.0

isVisible = true
}

fun stopSelection() {
isVisible = false

lastSelection.clear()

lastSelection.addAll(
world.getEntitiesInRange(Rectangle2D(translateX, translateY, width, height))
)
}

override fun onUpdate(tpf: Double) {
if (isVisible) {
val dx = input.mouseXUI - selectionStart.x
val dy = input.mouseYUI - selectionStart.y

if (dx > 0) {
width = dx
} else {
translateX = input.mouseXUI
width = -dx
}

if (dy > 0) {
height = dy
} else {
translateY = input.mouseYUI
height = -dy
}
}
}

override fun getNode(): Node {
return this
}

override fun dispose() { }
}

0 comments on commit 5fb6e02

Please sign in to comment.