66
77package com.almasb.fxgl.dsl.components
88
9- import com.almasb.fxgl.app.scene.Viewport
109import com.almasb.fxgl.dsl.FXGL
1110import com.almasb.fxgl.entity.component.Component
11+ import javafx.geometry.Rectangle2D
1212
1313/* *
1414 * A component that keeps an entity within the viewport.
1515 * Entities with physics enabled are not supported.
16- * Do NOT use this component if viewport is bound to an entity.
1716 *
1817 * @author Almas Baimagambetov (almaslvl@gmail.com)
1918 */
20- class KeepOnScreenComponent : Component () {
21-
22- private lateinit var viewport: Viewport
19+ open class KeepInBoundsComponent (var bounds : Rectangle2D ) : Component() {
2320
2421 /* *
25- * keep on screen in X axis.
22+ * Keep in bounds in X axis.
2623 */
2724 var isHorizontal = true
2825
2926 /* *
30- * keep on screen in Y axis.
27+ * Keep in bounds in Y axis.
3128 */
3229 var isVertical = true
3330
34- override fun onAdded () {
35- viewport = FXGL .getGameScene().viewport
36- }
37-
3831 override fun onUpdate (tpf : Double ) {
3932 blockWithBBox()
4033 }
4134
4235 private fun blockWithBBox () {
4336 if (isHorizontal) {
44- if (getEntity().x < viewport.x ) {
45- getEntity().x = viewport.x
46- } else if (getEntity().rightX > viewport.x + viewport.width ) {
47- getEntity().x = viewport.x + viewport.width - getEntity().width
37+ if (getEntity().x < bounds.minX ) {
38+ getEntity().x = bounds.minX
39+ } else if (getEntity().rightX > bounds.maxX ) {
40+ getEntity().x = bounds.maxX - getEntity().width
4841 }
4942 }
5043
5144 if (isVertical) {
52- if (getEntity().y < viewport.y ) {
53- getEntity().y = viewport.y
54- } else if (getEntity().bottomY > viewport.y + viewport.height ) {
55- getEntity().y = viewport.y + viewport.height - getEntity().height
45+ if (getEntity().y < bounds.minY ) {
46+ getEntity().y = bounds.minY
47+ } else if (getEntity().bottomY > bounds.maxY ) {
48+ getEntity().y = bounds.maxY - getEntity().height
5649 }
5750 }
5851 }
@@ -73,4 +66,17 @@ class KeepOnScreenComponent : Component() {
7366 }
7467
7568 override fun isComponentInjectionRequired (): Boolean = false
69+ }
70+
71+ /* *
72+ * A component that keeps an entity within the viewport.
73+ * Entities with physics enabled are not supported.
74+ * Do NOT use this component if viewport is bound to an entity.
75+ */
76+ class KeepOnScreenComponent : KeepInBoundsComponent (Rectangle2D .EMPTY ) {
77+
78+ override fun onUpdate (tpf : Double ) {
79+ bounds = FXGL .getGameScene().viewport.visibleArea
80+ super .onUpdate(tpf)
81+ }
7682}
0 commit comments