Class GameSceneView
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.gpu.RenderView
com.codename1.gaming.GameView
com.codename1.gaming.level.GameSceneView
- All Implemented Interfaces:
Animation, Editable, StyleListener, Iterable<Component>
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).
-
Field Summary
Fields inherited from class Component
BASELINE, BOTTOM, BRB_CENTER_OFFSET, BRB_CONSTANT_ASCENT, BRB_CONSTANT_DESCENT, BRB_OTHER, CENTER, CROSSHAIR_CURSOR, DEFAULT_CURSOR, DRAG_REGION_IMMEDIATELY_DRAG_X, DRAG_REGION_IMMEDIATELY_DRAG_XY, DRAG_REGION_IMMEDIATELY_DRAG_Y, DRAG_REGION_LIKELY_DRAG_X, DRAG_REGION_LIKELY_DRAG_XY, DRAG_REGION_LIKELY_DRAG_Y, DRAG_REGION_NOT_DRAGGABLE, DRAG_REGION_POSSIBLE_DRAG_X, DRAG_REGION_POSSIBLE_DRAG_XY, DRAG_REGION_POSSIBLE_DRAG_Y, E_RESIZE_CURSOR, HAND_CURSOR, LEFT, MOVE_CURSOR, N_RESIZE_CURSOR, NE_RESIZE_CURSOR, NW_RESIZE_CURSOR, RIGHT, S_RESIZE_CURSOR, SE_RESIZE_CURSOR, SW_RESIZE_CURSOR, TEXT_CURSOR, TOP, W_RESIZE_CURSOR, WAIT_CURSOR -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionintaddScore(int delta) Addsdeltato the score and returns the new total.protected SpriteThe player sprite the arcade behavior drives: an element flaggedplayer = truewins, else the firstplayer/heroasset.protected voidbuildModels(GraphicsDevice device) Builds the 3D models for the level.protected voidcheckPickups(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 GameElementTheGameElementa sprite was realized from -- itsSprite#getUserData()-- ornullif the sprite did not come from a level element.findAllByAsset(String assetId) Every sprite stamped from the given asset id, in z-order -- handy for a "collect all the coins" loop.protected SpritefindByAsset(String assetId) The first sprite stamped from the given asset id (e.g."player","coin"), ornull.protected SpritefindByName(String name) The first sprite in the scene whose source element has the givenname(the name typed in the Inspector), ornull.getLevel()intgetLives()Remaining lives, or-1until#setLives(int)is called.The isometric projection used to place a board level (valid after the first sized frame).intgetScore()The running score (starts at zero).booleanprotected booleanisCollectible(String assetId) Whether an asset id is a collectible (the default arcade behavior scores and removes it).protected booleanWhether an asset id is an enemy (the default arcade behavior patrols it and costs a life on contact).booleanTrue once#setLives(int)has been given a count that has since reached zero -- the standard "game over" test (false while lives are uninitialized).protected booleanisSolidAt(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).intloseLife()Decrements the life count (never below zero) and returns what remains.protected booleanCalled when the player touches a collectible.protected voidonPlayerHit(Sprite enemy) Called when the player touches an enemy.protected voidonSetup(GraphicsDevice device) Override to allocate GPU resources (meshes, textures,Models) once the GPU device is ready.protected voidonUpdate(double deltaSeconds) Override to advance game logic each frame.protected booleanWhether two sprites' bounding boxes overlap -- a null-safe shorthand forSprite#intersects(Sprite), the usual "did they touch?" collision test.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.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.voidsetLives(int lives) voidsetScore(int score) protected voidupdate(double deltaSeconds) Advance the game by the given amount of time.protected voidupdateArcade(double deltaSeconds) Runs one arcade frame: player physics, enemy patrol, pickups, and the follow camera.protected voidupdateEnemies(double deltaSeconds) Default enemy behavior: every#isEnemy(String)sprite patrols horizontally at itsspeedproperty, turning at walls and level edges.protected voidupdatePlayer(Sprite player, double deltaSeconds) Default player physics: run with Left/Right, jump on Up/Fire (edge-triggered), gravity from the level'sgravityproperty, jump height from the player'sjumpHeightproperty, stopped by solid tiles, respawning if it falls out.Methods inherited from class GameView
addModel, deinitialize, frame, getCamera, getControls, getFixedTimestep, getInput, getInterpolationAlpha, getLight, getScene, handlesInput, initComponent, isPaused, isRunning, keyPressed, keyReleased, pause, pointerDragged, pointerPressed, pointerReleased, removeModel, resume, setClearColor, setFixedTimestep, setup, start, stopMethods inherited from class RenderView
getPeer, getRenderer, isContinuous, isSupported, requestRender, setContinuousMethods inherited from class Container
add, add, add, add, add, add, addAll, addComponent, addComponent, addComponent, addComponent, animateHierarchy, animateHierarchyAndWait, animateHierarchyFade, animateHierarchyFadeAndWait, animateLayout, animateLayoutAndWait, animateLayoutFade, animateLayoutFadeAndWait, animateUnlayout, animateUnlayoutAndWait, applyRTL, calcPreferredSize, cancelRepaints, clearClientProperties, constrainHeightWhenScrollable, constrainWidthWhenScrollable, contains, createAnimateHierarchy, createAnimateHierarchyFade, createAnimateLayout, createAnimateLayoutFade, createAnimateLayoutFadeAndWait, createAnimateMotion, createAnimateUnlayout, createReplaceTransition, dragInitiated, drop, encloseIn, encloseIn, findDropTargetAt, findFirstFocusable, fireClicked, flushReplace, forceRevalidate, getBottomGap, getChildrenAsList, getClosestComponentTo, getComponentAt, getComponentAt, getComponentCount, getComponentIndex, getGridPosX, getGridPosY, getLayout, getLayoutHeight, getLayoutWidth, getLeadComponent, getLeadParent, getResponderAt, getSafeAreaRoot, getScrollIncrement, getSideGap, getUIManager, initLaf, invalidate, isEnabled, isSafeArea, isSafeAreaRoot, isScrollableX, isScrollableY, isSelectableInteraction, isSurface, iterator, iterator, layoutContainer, morph, morphAndWait, paint, paintComponentBackground, paintGlass, paramString, pointerPressed, refreshTheme, removeAll, removeComponent, replace, replace, replaceAndWait, replaceAndWait, replaceAndWait, revalidate, revalidateLater, revalidateWithAnimationSafety, scrollComponentToVisible, setCellRenderer, setEnabled, setLayout, setLeadComponent, setSafeArea, setSafeAreaRoot, setScrollable, setScrollableX, setScrollableY, setScrollIncrement, setShouldCalcPreferredSize, setShouldLayout, setUIManager, updateTabIndicesMethods inherited from class Component
addDragFinishedListener, addDragOverListener, addDropListener, addFocusListener, addLongPressListener, addPointerDraggedListener, addPointerPressedListener, addPointerReleasedListener, addPullToRefresh, addScrollListener, addStateChangeListener, animate, announceForAccessibility, bindProperty, blocksSideSwipe, calcScrollSize, contains, containsOrOwns, createStyleAnimation, deinitializeCustomStyle, dragEnter, dragExit, dragFinished, draggingOver, drawDraggedImage, focusGained, focusLost, getAbsoluteX, getAbsoluteY, getAccessibilityText, getAllStyles, getAnimationManager, getBaseline, getBaselineResizeBehavior, getBindablePropertyNames, getBindablePropertyTypes, getBorder, getBoundPropertyValue, getBounds, getBounds, getClientProperty, getCloudBoundProperty, getCloudDestinationProperty, getComponentForm, getComponentState, getCursor, getDefaultDragTransparency, getDirtyRegion, getDisabledStyle, getDraggedx, getDraggedy, getDragImage, getDragRegionStatus, getDragSpeed, getDragTransparency, getEditingDelegate, getHeight, getInlineAllStyles, getInlineDisabledStyles, getInlinePressedStyles, getInlineSelectedStyles, getInlineStylesTheme, getInlineUnselectedStyles, getInnerHeight, getInnerPreferredH, getInnerPreferredW, getInnerWidth, getInnerX, getInnerY, getLabelForComponent, getName, getNativeOverlay, getNextFocusDown, getNextFocusLeft, getNextFocusRight, getNextFocusUp, getOuterHeight, getOuterPreferredH, getOuterPreferredW, getOuterWidth, getOuterX, getOuterY, getOwner, getParent, getPreferredH, getPreferredSize, getPreferredSizeStr, getPreferredTabIndex, getPreferredW, getPressedStyle, getPropertyNames, getPropertyTypeNames, getPropertyTypes, getPropertyValue, getSameHeight, getSameWidth, getScrollable, getScrollAnimationSpeed, getScrollDimension, getScrollOpacity, getScrollOpacityChangeSpeed, getScrollX, getScrollY, getSelectCommandText, getSelectedRect, getSelectedStyle, getStyle, getTabIndex, getTensileLength, getTextSelectionSupport, getTooltip, getUIID, getUnselectedStyle, getVisibleBounds, getVisibleBounds, getWidth, getX, getY, growShrink, hasFixedPreferredSize, hasFocus, hideNativeOverlay, initCustomStyle, initDisabledStyle, initPressedStyle, initSelectedStyle, initUnselectedStyle, installDefaultPainter, isAlwaysTensile, isBlockLead, isCellRenderer, isChildOf, isDragActivated, isDragAndDropOperation, isDraggable, isDragRegion, isDropTarget, isEditable, isEditing, isFlatten, isFocusable, isGrabsPointerEvents, isHidden, isHidden, isHideInLandscape, isHideInPortrait, isHScrollThumbGrabbed, isHScrollThumbHover, isIgnorePointerEvents, isInClippingRegion, isInitialized, isOpaque, isOwnedBy, isPinchBlocksDragAndDrop, isRippleEffect, isRTL, isScrollable, isScrollVisible, isSetCursorSupported, isSmoothScrolling, isSnapToGrid, isStickyDrag, isTactileTouch, isTactileTouch, isTensileDragEnabled, isTraversable, isVisible, isVScrollThumbGrabbed, isVScrollThumbHover, keyRepeated, laidOut, longKeyPress, longPointerPress, onScrollX, onScrollY, onSetFocusable, paintBackground, paintBackgrounds, paintBorder, paintBorderBackground, paintComponent, paintComponent, paintIntersectingComponentsAbove, paintLock, paintLockRelease, paintRippleOverlay, paintScrollbars, paintScrollbarX, paintScrollbarY, paintShadows, parsePreferredSize, pinch, pinch, pinchReleased, pointerDragged, pointerHover, pointerHoverPressed, pointerHoverReleased, pointerReleased, putClientProperty, refreshTheme, refreshTheme, remove, removeDragFinishedListener, removeDragOverListener, removeDropListener, removeFocusListener, removeLongPressListener, removePointerDraggedListener, removePointerPressedListener, removePointerReleasedListener, removeScrollListener, removeStateChangeListener, repaint, repaint, requestFocus, resetFocusable, respondsToPointerEvents, scrollRectToVisible, scrollRectToVisible, setAccessibilityText, setAlwaysTensile, setBlockLead, setBoundPropertyValue, setCloudBoundProperty, setCloudDestinationProperty, setComponentState, setCursor, setDefaultDragTransparency, setDirtyRegion, setDisabledStyle, setDraggable, setDragTransparency, setDropTarget, setEditingDelegate, setFlatten, setFocus, setFocusable, setGrabsPointerEvents, setHandlesInput, setHeight, setHidden, setHidden, setHideInLandscape, setHideInPortrait, setHorizontalScrollBounds, setIgnorePointerEvents, setInitialized, setInlineAllStyles, setInlineDisabledStyles, setInlinePressedStyles, setInlineSelectedStyles, setInlineStylesTheme, setInlineUnselectedStyles, setIsScrollVisible, setLabelForComponent, setName, setNextFocusDown, setNextFocusLeft, setNextFocusRight, setNextFocusUp, setOpaque, setOwner, setPinchBlocksDragAndDrop, setPreferredH, setPreferredSize, setPreferredSizeStr, setPreferredTabIndex, setPreferredW, setPressedStyle, setPropertyValue, setPullToRefresh, setRippleEffect, setRTL, setSameHeight, setSameSize, setSameWidth, setScrollAnimationSpeed, setScrollOpacityChangeSpeed, setScrollSize, setScrollVisible, setScrollX, setScrollY, setSelectCommandText, setSelectedStyle, setSize, setSmoothScrolling, setSnapToGrid, setTabIndex, setTactileTouch, setTensileDragEnabled, setTensileLength, setTooltip, setTraversable, setUIID, setUIID, setUIIDFinal, setUnselectedStyle, setVerticalScrollBounds, setVisible, setWidth, setX, setY, shouldBlockSideSwipe, shouldBlockSideSwipeLeft, shouldBlockSideSwipeRight, shouldRenderComponentSelection, showNativeOverlay, startEditingAsync, stopEditing, stripMarginAndPadding, styleChanged, toImage, toString, unbindProperty, updateNativeOverlay, visibleBoundsContains
-
Constructor Details
-
GameSceneView
-
-
Method Details
-
getLevel
-
getCatalog
-
update
protected void update(double deltaSeconds) Advance the game by the given amount of time. Called once per frame (or repeatedly at a fixed interval when#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) Override to advance game logic each frame. The default does nothing. -
getProjection
The isometric projection used to place a board level (valid after the first sized frame). -
elementOf
TheGameElementa sprite was realized from -- itsSprite#getUserData()-- ornullif the sprite did not come from a level element. This is the bridge back to the typedlives/value/speednumbers you set in the editor. -
findByName
-
findByAsset
-
findAllByAsset
-
overlaps
-
getScore
public int getScore()The running score (starts at zero). Add to it with#addScore(int). -
setScore
public void setScore(int score) -
addScore
public int addScore(int delta) Addsdeltato the score and returns the new total. -
getLives
public int getLives()Remaining lives, or-1until#setLives(int)is called. The generated scene seeds this from the player'slivesproperty. -
setLives
public void setLives(int lives) -
loseLife
public int loseLife()Decrements the life count (never below zero) and returns what remains. -
isGameOver
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). -
setArcadeBehavior
Enables (or disables) the built-in 2D arcade behavior -- gravity, run/jump, tile collision, enemy patrol and pickups -- that the editor preview shows. Off by default. Has no effect on board or 3D levels. -
isArcadeBehavior
public boolean isArcadeBehavior() -
setFollowCamera
Whether the arcade behavior scrolls the scene camera to follow the player (on by default) -- this is what makes a parallax background scroll. -
updateArcade
protected void updateArcade(double deltaSeconds) Runs one arcade frame: player physics, enemy patrol, pickups, and the follow camera. Called automatically before#onUpdate(double)when#setArcadeBehavior(boolean)is on and the level is 2D. -
arcadePlayer
The player sprite the arcade behavior drives: an element flaggedplayer = truewins, else the firstplayer/heroasset. Cached; also seeds#setLives(int)from the player'slivesproperty on first resolve. -
updatePlayer
Default player physics: run with Left/Right, jump on Up/Fire (edge-triggered), gravity from the level'sgravityproperty, jump height from the player'sjumpHeightproperty, 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) Default enemy behavior: every#isEnemy(String)sprite patrols horizontally at itsspeedproperty, turning at walls and level edges. -
checkPickups
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). -
onPickup
Called when the player touches a collectible. The default adds the item'svalueproperty to the score and returnstrueto consume it. Override for power-ups: read the asset id / properties, change state, and return whether to remove the item. -
onPlayerHit
Called when the player touches an enemy. The default costs a life and respawns the player at its start. Override for HP, knockback, invulnerability frames, checkpoints or a death screen. -
isCollectible
Whether an asset id is a collectible (the default arcade behavior scores and removes it). Defaults tocoin/gem/star/token; override to add yours. -
isEnemy
Whether an asset id is an enemy (the default arcade behavior patrols it and costs a life on contact). Defaults toslime/enemy*/npc*; override yours. -
isSolidAt
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). The collision query the default player/enemy physics uses; override for one-way platforms etc. -
onSetup
Override to allocate GPU resources (meshes, textures,
Models) once the GPU device is ready. Invoked once on the render thread before the first frame -- the only place you can callcom.codename1.gpu.Primitives/com.codename1.gpu.GltfLoader, which need the device. The default does nothing.Parameters
device: the GPU device for creating meshes, textures and buffers
-
buildModels
Builds the 3D models for the level. The default gives every element a unit cube (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. withcom.codename1.gpu.GltfLoader) keyed off the element's asset id.
-