Class GameView
- All Implemented Interfaces:
Animation, Editable, StyleListener, Iterable<Component>
A GPU accelerated game surface: a com.codename1.gpu.RenderView that hosts a
SpriteRenderer over a Scene and calls your #update(double) once per frame.
Subclass it, build your world by adding Sprites to #getScene(), advance the
game in #update(double), add the view to a com.codename1.ui.Form and call
#start():
class MyGame extends GameView {
final Sprite player = new Sprite(playerImage);
MyGame() { getScene().add(player); player.setPosition(160, 240); }
protected void update(double dt) {
if (getInput().isGameKeyDown(Display.GAME_RIGHT)) {
player.setX(player.getX() + 200 * dt); // 200 px/second
}
}
}
Form f = new Form("Game", new BorderLayout());
MyGame game = new MyGame();
f.add(BorderLayout.CENTER, game);
f.show();
game.start();
Rendering is GPU driven: the underlying RenderView runs the frame loop (a
display link on device, the software rasterizer in the simulator), so there is
no EDT busy loop. Drawing is handled for you by the SpriteRenderer -- you only
position sprites. The deltaSeconds passed to #update(double) is the wall
clock time since the previous frame; multiply movement by it to stay framerate
independent. With #setFixedTimestep(double) the update is stepped at a fixed
interval for deterministic physics, and #getInterpolationAlpha() gives a 0..1
blend factor.
#update(double) runs on the render thread together with drawing. Keep it non
blocking -- offload asset loading to a background thread and hand the result
back with com.codename1.ui.CN#callSerially(java.lang.Runnable).
-
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 TypeMethodDescriptionvoidAdds a 3DModelto be drawn in the perspective camera alongside the sprites.protected voidInvoked to indicate that the component initialization is being reversed since the component was detached from the container hierarchy.voidframe(double deltaSeconds) Drives game logic each frame -- invoked by theSpriteRendererbefore the scene is drawn.The camera this view renders through.The on-screen touch controls for this view (a virtual joystick and buttons).doublegetInput()The pollable input state for this view.doubleThe 0..1 fraction of a fixed step left after the last update, for interpolating rendered positions.getLight()The directional light shading lit 3DModels in perspective mode.getScene()The scene drawn by this view; add and removeSprites here.booleanWhile running the view consumes all key events (including the directional pad and fire button) so they are not stolen for focus traversal.protected voidAllows subclasses to bind functionality that relies on fully initialized and "ready for action" component statebooleanisPaused()booleanvoidkeyPressed(int keyCode) If this Component is focused, the key pressed event will call this methodvoidkeyReleased(int keyCode) If this Component is focused, the key released event will call this methodprotected voidonSetup(GraphicsDevice device) Override to allocate GPU resources (meshes, textures,Models) once the GPU device is ready.voidpause()Pauses updates; frames still render but#update(double)is not called.voidpointerDragged(int[] x, int[] y) If this Component is focused, the pointer dragged event will call this methodvoidpointerPressed(int[] x, int[] y) If this Component is focused, the pointer pressed event will call this methodvoidpointerReleased(int[] x, int[] y) If this Component is focused, the pointer released event will call this methodvoidremoveModel(Model model) Removes a previously added 3DModel.voidresume()Resumes after#pause().voidsetClearColor(int argb) Sets the ARGB color the view is cleared to each frame.voidsetFixedTimestep(double seconds) Sets a fixed update interval in seconds (0 disables, the default).voidsetup(GraphicsDevice device) Forwards GPU setup to#onSetup(com.codename1.gpu.GraphicsDevice).voidstart()Starts the game loop (continuous rendering).voidstop()Stops the game loop (no further frames until#start()).protected abstract voidupdate(double deltaSeconds) Advance the game by the given amount of time.Methods 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
-
GameView
public GameView()
-
-
Method Details
-
update
protected abstract 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). -
getScene
The scene drawn by this view; add and removeSprites here. -
getInput
The pollable input state for this view. -
getControls
The on-screen touch controls for this view (a virtual joystick and buttons). Add controls to it to make the game playable on touch devices; whatever you add feeds the sameGameInputyour keyboard handling already reads. -
getCamera
The camera this view renders through. It starts in 2D mode; callGameCamera#setPerspective(float, float, float)on it to switch the view into a 3D perspective with billboarded sprites. -
getLight
The directional light shading lit 3DModels in perspective mode. -
addModel
Adds a 3DModelto be drawn in the perspective camera alongside the sprites. Build models from#onSetup(com.codename1.gpu.GraphicsDevice), where the GPU device is available. -
removeModel
Removes a previously added 3DModel. -
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
-
setup
Forwards GPU setup to#onSetup(com.codename1.gpu.GraphicsDevice). -
setClearColor
public void setClearColor(int argb) Sets the ARGB color the view is cleared to each frame. -
start
public void start()Starts the game loop (continuous rendering). Safe to call before or after the view is shown. -
stop
public void stop()Stops the game loop (no further frames until#start()). -
pause
public void pause()Pauses updates; frames still render but#update(double)is not called. -
resume
public void resume()Resumes after#pause(). -
isRunning
public boolean isRunning() -
isPaused
public boolean isPaused() -
setFixedTimestep
public void setFixedTimestep(double seconds) Sets a fixed update interval in seconds (0 disables, the default). With a fixed timestep#update(double)may be called several times per frame to catch up, and#getInterpolationAlpha()returns the leftover fraction. -
getFixedTimestep
public double getFixedTimestep() -
getInterpolationAlpha
public double getInterpolationAlpha()The 0..1 fraction of a fixed step left after the last update, for interpolating rendered positions. Always 1 with a variable timestep. -
initComponent
protected void initComponent()Allows subclasses to bind functionality that relies on fully initialized and "ready for action" component state Re-applies the running state once the GPU peer exists and starts listening for pointer events at the form level.- Overrides:
initComponentin classRenderView
-
deinitialize
protected void deinitialize()Invoked to indicate that the component initialization is being reversed since the component was detached from the container hierarchy. This allows the component to deregister animators and cleanup after itself. This method is the opposite of the initComponent() method. Stops listening for pointer events when detached.- Overrides:
deinitializein classComponent
-
frame
public void frame(double deltaSeconds) Drives game logic each frame -- invoked by theSpriteRendererbefore the scene is drawn. -
handlesInput
public boolean handlesInput()While running the view consumes all key events (including the directional pad and fire button) so they are not stolen for focus traversal.- Overrides:
handlesInputin classComponent- Returns:
- true if key events are being used for focus traversal ; otherwise false
-
keyPressed
public void keyPressed(int keyCode) Description copied from class:ContainerIf this Component is focused, the key pressed event will call this method
Parameters
keyCode: the key code value to indicate a physical key.
- Overrides:
keyPressedin classContainer
-
keyReleased
public void keyReleased(int keyCode) Description copied from class:ContainerIf this Component is focused, the key released event will call this method
Parameters
keyCode: the key code value to indicate a physical key.
- Overrides:
keyReleasedin classContainer
-
pointerPressed
public void pointerPressed(int[] x, int[] y) Description copied from class:ComponentIf this Component is focused, the pointer pressed event will call this method
Parameters
-
x: the pointer x coordinate -
y: the pointer y coordinate
- Overrides:
pointerPressedin classComponent
-
-
pointerDragged
public void pointerDragged(int[] x, int[] y) Description copied from class:ComponentIf this Component is focused, the pointer dragged event will call this method
Parameters
-
x: the pointer x coordinate -
y: the pointer y coordinate
- Overrides:
pointerDraggedin classComponent
-
-
pointerReleased
public void pointerReleased(int[] x, int[] y) Description copied from class:ComponentIf this Component is focused, the pointer released event will call this method
Parameters
-
x: the pointer x coordinate -
y: the pointer y coordinate
- Overrides:
pointerReleasedin classComponent
-
-