public class GameSceneView
- Object
- Component
- Container
- RenderView
- GameView
- GameSceneView
ImplementsAnimation, Editable, Iterable<Component>, StyleListener
A turnkey GameView that plays a GameLevel: it wires the whole lifecycle so a
generated game scene can be a thin subclass that only adds behavior.
- 2D levels are realized into the scene immediately.
- board levels are realized on the first sized frame, once an
IsoProjectioncan be fitted to the view. - 3D levels set up the perspective camera and the primary light, and build a
Modelper element inGameView#onSetup(com.codename1.gpu.GraphicsDevice)(the only place the GPU device exists); override#buildModels(GraphicsDevice)to supply real meshes instead of the default per-element cube.
Game logic goes in #onUpdate(double) (a no-op by default) – the scene’s sprite
animations are advanced by the renderer, so do not call Scene#update(double).
Constructors
public GameSceneView(GameLevel level, AssetCatalog catalog) |
Methods
public GameLevel getLevel() | |
public AssetCatalog getCatalog() | |
protected void update(double deltaSeconds) | Advance the game by the given amount of time. |
protected void onUpdate(double deltaSeconds) | Override to advance game logic each frame. |
public IsoProjection getProjection() | The isometric projection used to place a board level (valid after the first sized frame). |
protected GameElement elementOf(Sprite sprite) | The GameElement a sprite was realized from – its Sprite#getUserData() – or null if the sprite did not come from a level element. |
protected Sprite findByName(String name) | The first sprite in the scene whose source element has the given name (the name typed in the Inspector), or null. |
protected Sprite findByAsset(String assetId) | The first sprite stamped from the given asset id (e.g. "player", "coin"), or null. |
protected List<Sprite> findAllByAsset(String assetId) | Every sprite stamped from the given asset id, in z-order – handy for a “collect all the coins” loop. |
protected boolean overlaps(Sprite a, Sprite b) | Whether two sprites’ bounding boxes overlap – a null-safe shorthand for Sprite#intersects(Sprite), the usual “did they touch?” collision test. |
public int getScore() | The running score (starts at zero). |
public void setScore(int score) | |
public int addScore(int delta) | Adds delta to the score and returns the new total. |
public int getLives() | Remaining lives, or -1 until #setLives(int) is called. |
public void setLives(int lives) | |
public int loseLife() | Decrements the life count (never below zero) and returns what remains. |
public boolean isGameOver() | True once #setLives(int) has been given a count that has since reached zero – the standard “game over” test (false while lives are uninitialized). |
public GameSceneView setArcadeBehavior(boolean on) | Enables (or disables) the built-in 2D arcade behavior – gravity, run/jump, tile collision, enemy patrol and pickups – that the editor preview shows. |
public boolean isArcadeBehavior() | |
public GameSceneView setFollowCamera(boolean on) | Whether the arcade behavior scrolls the scene camera to follow the player (on by default) – this is what makes a parallax background scroll. |
protected void updateArcade(double deltaSeconds) | Runs one arcade frame: player physics, enemy patrol, pickups, and the follow camera. |
protected Sprite arcadePlayer() | The player sprite the arcade behavior drives: an element flagged player = true wins, else the first player/hero asset. |
protected void updatePlayer(Sprite player, double deltaSeconds) | Default player physics: run with Left/Right, jump on Up/Fire (edge-triggered), gravity from the level’s gravity property, jump height from the player’s jumpHeight property, stopped by solid tiles, respawning if it falls out. |
protected void updateEnemies(double deltaSeconds) | Default enemy behavior: every #isEnemy(String) sprite patrols horizontally at its speed property, turning at walls and level edges. |
protected void checkPickups(Sprite player) | Default pickups: when the player overlaps a #isCollectible(String) sprite, #onPickup(Sprite) fires (scores and consumes it); when it overlaps an #isEnemy(String) sprite, #onPlayerHit(Sprite) fires (costs a life). |
protected boolean onPickup(Sprite item) | Called when the player touches a collectible. |
protected void onPlayerHit(Sprite enemy) | Called when the player touches an enemy. |
protected boolean isCollectible(String assetId) | Whether an asset id is a collectible (the default arcade behavior scores and removes it). |
protected boolean isEnemy(String assetId) | Whether an asset id is an enemy (the default arcade behavior patrols it and costs a life on contact). |
protected boolean isSolidAt(double cx, double cy, double hw, double hh) | Whether a box centered at (cx, cy) with half-size (hw, hh) overlaps any solid tile (a non-empty cell of a visible tile layer). |
protected void onSetup(GraphicsDevice device) | Override to allocate GPU resources (meshes, textures, Models) once the GPU device is ready. |
protected void buildModels(GraphicsDevice device) | Builds the 3D models for the level. |
Inherited fields
From Component
DEFAULT_CURSOR, CROSSHAIR_CURSOR, TEXT_CURSOR, WAIT_CURSOR, SW_RESIZE_CURSOR, SE_RESIZE_CURSOR, NW_RESIZE_CURSOR, NE_RESIZE_CURSOR, N_RESIZE_CURSOR, S_RESIZE_CURSOR, W_RESIZE_CURSOR, E_RESIZE_CURSOR, HAND_CURSOR, MOVE_CURSOR, DRAG_REGION_NOT_DRAGGABLE, DRAG_REGION_POSSIBLE_DRAG_X, DRAG_REGION_POSSIBLE_DRAG_Y, DRAG_REGION_POSSIBLE_DRAG_XY, DRAG_REGION_LIKELY_DRAG_X, DRAG_REGION_LIKELY_DRAG_Y, DRAG_REGION_LIKELY_DRAG_XY, DRAG_REGION_IMMEDIATELY_DRAG_X, DRAG_REGION_IMMEDIATELY_DRAG_Y, DRAG_REGION_IMMEDIATELY_DRAG_XY, BRB_CONSTANT_ASCENT, BRB_CONSTANT_DESCENT, BRB_CENTER_OFFSET, BRB_OTHER, CENTER, TOP, LEFT, BOTTOM, RIGHT, BASELINE
Inherited methods
From GameView
getScene, getInput, getControls, getCamera, getLight, addModel, removeModel, setClearColor, start, stop, pause, resume, isRunning, isPaused, setFixedTimestep, getFixedTimestep, getInterpolationAlpha, initComponent, deinitialize, handlesInput, keyPressed, keyReleased, pointerPressed, pointerDragged, pointerReleased
From Container
encloseIn, encloseIn, initLaf, getUIManager, setUIManager, isSurface, add, addAll, add, add, add, add, add, getLeadComponent, setLeadComponent, getLeadParent, getLayout, setLayout, invalidate, setShouldLayout, setShouldCalcPreferredSize, getLayoutWidth, getLayoutHeight, applyRTL, constrainWidthWhenScrollable, constrainHeightWhenScrollable, addComponent, addComponent, addComponent, addComponent, replaceAndWait, replaceAndWait, replace, replaceAndWait, replace, createReplaceTransition, isEnabled, setEnabled, removeComponent, cancelRepaints, flushReplace, removeAll, revalidateWithAnimationSafety, revalidate, revalidateLater, forceRevalidate, clearClientProperties, paint, paintGlass, layoutContainer, isSafeArea, setSafeArea, isSafeAreaRoot, getSafeAreaRoot, setSafeAreaRoot, getComponentCount, getComponentAt, getComponentIndex, contains, scrollComponentToVisible, getClosestComponentTo, getResponderAt, getComponentAt, findDropTargetAt, pointerPressed, calcPreferredSize, paramString, refreshTheme, isScrollableX, setScrollableX, isScrollableY, setScrollableY, getSideGap, getBottomGap, setScrollable, setCellRenderer, getScrollIncrement, setScrollIncrement, findFirstFocusable, dragInitiated, fireClicked, isSelectableInteraction, getGridPosY, paintComponentBackground, getGridPosX, animateHierarchyAndWait, createAnimateHierarchy, animateHierarchy, animateHierarchyFadeAndWait, createAnimateHierarchyFade, animateHierarchyFade, animateLayoutFadeAndWait, createAnimateLayoutFadeAndWait, animateLayoutFade, createAnimateLayoutFade, animateLayoutAndWait, animateLayout, updateTabIndices, createAnimateLayout, drop, createAnimateMotion, morph, morphAndWait, animateUnlayout, animateUnlayoutAndWait, createAnimateUnlayout, getChildrenAsList, iterator, iterator
From Component
setSameSize, isSetCursorSupported, parsePreferredSize, getDefaultDragTransparency, setDefaultDragTransparency, getEditingDelegate, setEditingDelegate, getCursor, setCursor, showNativeOverlay, hideNativeOverlay, updateNativeOverlay, getNativeOverlay, getAllStyles, getSameWidth, setSameWidth, getSameHeight, setSameHeight, getX, setX, getOuterX, getInnerX, getY, setY, getOuterY, getInnerY, isVisible, setVisible, getClientProperty, stripMarginAndPadding, putClientProperty, getDirtyRegion, setDirtyRegion, isOpaque, setOpaque, getWidth, setWidth, getOuterWidth, getInnerWidth, getHeight, setHeight, getOuterHeight, getInnerHeight, isDragRegion, getDragRegionStatus, getBaseline, getBaselineResizeBehavior, getPreferredSizeStr, setPreferredSizeStr, getPreferredSize, setPreferredSize, getScrollDimension, calcScrollSize, setScrollSize, getPreferredW, setPreferredW, getPreferredH, setPreferredH, getOuterPreferredH, getInnerPreferredH, getOuterPreferredW, getInnerPreferredW, setSize, getUIID, setUIID, setUIIDFinal, setUIID, getInlineAllStyles, setInlineAllStyles, getInlineSelectedStyles, setInlineSelectedStyles, getInlineUnselectedStyles, setInlineUnselectedStyles, getInlineDisabledStyles, setInlineDisabledStyles, getInlinePressedStyles, setInlinePressedStyles, remove, getParent, getOwner, setOwner, isOwnedBy, containsOrOwns, addFocusListener, removeFocusListener, addScrollListener, removeScrollListener, getSelectCommandText, setSelectCommandText, getLabelForComponent, setLabelForComponent, focusGained, focusLost, paintBackgrounds, paintShadows, getAbsoluteX, getAbsoluteY, isInClippingRegion, paintIntersectingComponentsAbove, paintScrollbars, paintScrollbarX, getScrollOpacity, getSelectedRect, paintScrollbarY, paintComponent, paintComponent, getBorder, getScrollable, paintBackground, isScrollable, getScrollX, setScrollX, getScrollY, setScrollY, onScrollX, onScrollY, getDraggedx, getDraggedy, contains, visibleBoundsContains, hasFixedPreferredSize, getBounds, getBounds, getVisibleBounds, getVisibleBounds, isFocusable, setFocusable, onSetFocusable, resetFocusable, getTabIndex, setTabIndex, getPreferredTabIndex, setPreferredTabIndex, isTraversable, setTraversable, setHandlesInput, consumesRawTextInput, hasFocus, setFocus, getComponentForm, getTopLevelContainer, repaint, repaint, longKeyPress, keyRepeated, registerForAnimation, deregisterFromAnimation, getAnimationManager, getScrollAnimationSpeed, setScrollAnimationSpeed, isBlockLead, setBlockLead, isIgnorePointerEvents, setIgnorePointerEvents, isRippleEffect, setRippleEffect, getInlineStylesTheme, setInlineStylesTheme, shouldRenderComponentSelection, isHideInLandscape, setHideInLandscape, createStyleAnimation, isSmoothScrolling, setSmoothScrolling, pointerHover, stopScrollMomentum, pointerHoverReleased, pointerHoverPressed, pinch, pinchReleased, pinch, rotation, isPinchBlocksDragAndDrop, setPinchBlocksDragAndDrop, getDragImage, getDragTransparency, setDragTransparency, toImage, drawDraggedImage, draggingOver, dragEnter, dragExit, addPullToRefresh, setPullToRefresh, respondsToPointerEvents, pointerDragged, isStickyDrag, isDragAndDropOperation, longPointerPress, pointerReleased, setVerticalScrollBounds, setHorizontalScrollBounds, isVScrollThumbGrabbed, isHScrollThumbGrabbed, isVScrollThumbHover, isHScrollThumbHover, isTensileDragEnabled, setTensileDragEnabled, getTextSelectionSupport, addDropListener, removeDropListener, addDragOverListener, removeDragOverListener, isNativeDragSource, setNativeDragSource, getNativeDragOperation, setNativeDragOperation, createNativeDragOperation, isNativeDropTarget, setNativeDropTarget, getAcceptedDropMimeTypes, setAcceptedDropMimeTypes, getAcceptedDropActions, setAcceptedDropActions, canAcceptNativeDrop, nativeDragEnter, nativeDragOver, nativeDragExit, nativeDrop, addNativeDropListener, removeNativeDropListener, addNativeDragOverListener, removeNativeDragOverListener, dragFinished, addDragFinishedListener, addStateChangeListener, removeStateChangeListener, addPointerPressedListener, addLongPressListener, addContextMenuListener, removeContextMenuListener, addMouseWheelListener, removeMouseWheelListener, addStylusListener, removeStylusListener, mouseWheel, paintRippleOverlay, removePointerPressedListener, removeLongPressListener, removeDragFinishedListener, addPointerReleasedListener, removePointerReleasedListener, addPointerDraggedListener, removePointerDraggedListener, getDragSpeed, getStyle, getPressedStyle, setPressedStyle, initUnselectedStyle, initPressedStyle, initDisabledStyle, initSelectedStyle, getUnselectedStyle, setUnselectedStyle, getSelectedStyle, setSelectedStyle, getDisabledStyle, setDisabledStyle, installDefaultPainter, requestFocus, toString, refreshTheme, refreshTheme, isDragActivated, animate, scrollRectToVisible, scrollRectToVisible, paintBorder, paintBorderBackground, isCellRenderer, isScrollVisible, setScrollVisible, setIsScrollVisible, startEditingAsync, stopEditing, isEditing, isEditable, laidOut, isInitialized, setInitialized, styleChanged, getNextFocusDown, setNextFocusDown, getNextFocusUp, setNextFocusUp, getNextFocusLeft, setNextFocusLeft, getNextFocusRight, setNextFocusRight, getName, setName, initCustomStyle, deinitializeCustomStyle, isRTL, setRTL, isTactileTouch, isTactileTouch, setTactileTouch, getPropertyNames, getPropertyTypes, getPropertyTypeNames, getPropertyValue, setPropertyValue, paintLockRelease, paintLock, isSnapToGrid, setSnapToGrid, shouldBlockSideSwipe, shouldBlockSideSwipeLeft, shouldBlockSideSwipeRight, blocksSideSwipe, isFlatten, setFlatten, getTensileLength, setTensileLength, isGrabsPointerEvents, setGrabsPointerEvents, getScrollOpacityChangeSpeed, setScrollOpacityChangeSpeed, growShrink, isAlwaysTensile, setAlwaysTensile, isDraggable, setDraggable, isDropTarget, setDropTarget, isChildOf, isHideInPortrait, setHideInPortrait, getBindablePropertyNames, getBindablePropertyTypes, bindProperty, unbindProperty, getBoundPropertyValue, setBoundPropertyValue, getCloudBoundProperty, setCloudBoundProperty, getCloudDestinationProperty, setCloudDestinationProperty, getComponentState, setComponentState, setHidden, isHidden, setHidden, isHidden, announceForAccessibility, getAccessibilityText, setAccessibilityText, getSemantics, getAccessibilityNode, accessibilityChanged, accessibilityChanged, getTooltip, setTooltip
Constructor details
GameSceneView
public GameSceneView(GameLevel level, AssetCatalog catalog)Method details
getLevel
public GameLevel getLevel()getCatalog
public AssetCatalog getCatalog()update
protected void update(double deltaSeconds)#setFixedTimestep(double) is used). Realizes a board level lazily once the view has a size, then
defers to #onUpdate(double).onUpdate
protected void onUpdate(double deltaSeconds)getProjection
public IsoProjection getProjection()elementOf
protected GameElement elementOf(Sprite sprite)GameElement a sprite was realized from – its Sprite#getUserData() –
or null if the sprite did not come from a level element. This is the bridge
back to the typed lives/value/speed numbers you set in the editor.findByName
protected Sprite findByName(String name)name (the
name typed in the Inspector), or null. The generated scene initializes a
field per named element with this.findByAsset
protected Sprite findByAsset(String assetId)"player", "coin"),
or null.findAllByAsset
protected List<Sprite> findAllByAsset(String assetId)null (empty when none match).overlaps
protected boolean overlaps(Sprite a, Sprite b)Sprite#intersects(Sprite), the usual “did they touch?” collision test.getScore
public int getScore()#addScore(int).setScore
public void setScore(int score)addScore
public int addScore(int delta)delta to the score and returns the new total.getLives
public int getLives()-1 until #setLives(int) is called. The generated scene
seeds this from the player’s lives property.setLives
public void setLives(int lives)loseLife
public int loseLife()isGameOver
public boolean isGameOver()#setLives(int) has been given a count that has since reached zero –
the standard “game over” test (false while lives are uninitialized).setArcadeBehavior
public GameSceneView setArcadeBehavior(boolean on)isArcadeBehavior
public boolean isArcadeBehavior()setFollowCamera
public GameSceneView setFollowCamera(boolean on)updateArcade
protected void updateArcade(double deltaSeconds)#onUpdate(double) when
#setArcadeBehavior(boolean) is on and the level is 2D.arcadePlayer
protected Sprite arcadePlayer()player = true wins, else the first player/hero asset. Cached; also
seeds #setLives(int) from the player’s lives property on first resolve.updatePlayer
protected void updatePlayer(Sprite player, double deltaSeconds)gravity property, jump height from the player’s
jumpHeight property, stopped by solid tiles, respawning if it falls out.
Override to change movement, or #setArcadeBehavior(boolean) off to opt out.updateEnemies
protected void updateEnemies(double deltaSeconds)#isEnemy(String) sprite patrols horizontally
at its speed property, turning at walls and level edges.checkPickups
protected void checkPickups(Sprite player)#isCollectible(String) sprite,
#onPickup(Sprite) fires (scores and consumes it); when it overlaps an
#isEnemy(String) sprite, #onPlayerHit(Sprite) fires (costs a life).onPickup
protected boolean onPickup(Sprite item)value property to the score and returns true to consume it. Override for
power-ups: read the asset id / properties, change state, and return whether
to remove the item.onPlayerHit
protected void onPlayerHit(Sprite enemy)isCollectible
protected boolean isCollectible(String assetId)coin/gem/star/token; override to add yours.isEnemy
protected boolean isEnemy(String assetId)slime/enemy*/npc*; override yours.isSolidAt
protected boolean isSolidAt(double cx, double cy, double hw, double hh)(cx, cy) with half-size (hw, hh) overlaps any
solid tile (a non-empty cell of a visible tile layer). The collision query
the default player/enemy physics uses; override for one-way platforms etc.onSetup
protected void onSetup(GraphicsDevice device)Models) once the GPU
device is ready. Invoked once on the render thread before the first frame –
the only place you can call com.codename1.gpu.Primitives /
com.codename1.gpu.GltfLoader, which need the device. The default does
nothing. For a 3D level, configures the camera + light and builds the models.Parameters
deviceGraphicsDevice- the GPU device for creating meshes, textures and buffers
buildModels
protected void buildModels(GraphicsDevice device)com.codename1.gpu.Primitives#cube) shaded with its asset’s base color and
placed/scaled from the element transform. Override to load real meshes (e.g. with
com.codename1.gpu.GltfLoader) keyed off the element’s asset id.