public abstract class GameView

  1. Object
  2. Component
  3. Container
  4. RenderView
  5. GameView

ImplementsAnimation, Editable, Iterable<Component>, StyleListener

Known subtypesGameSceneView

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).

Constructors

public GameView()

Methods

protected abstract void update(double deltaSeconds)Advance the game by the given amount of time.
public Scene getScene()The scene drawn by this view; add and remove Sprites here.
public GameInput getInput()The pollable input state for this view.
public TouchControls getControls()The on-screen touch controls for this view (a virtual joystick and buttons).
public GameCamera getCamera()The camera this view renders through.
public Light getLight()The directional light shading lit 3D Models in perspective mode.
public void addModel(Model model)Adds a 3D Model to be drawn in the perspective camera alongside the sprites.
public void removeModel(Model model)Removes a previously added 3D Model.
protected void onSetup(GraphicsDevice device)Override to allocate GPU resources (meshes, textures, Models) once the GPU device is ready.
public void setup(GraphicsDevice device)Invoked once after the GPU device is created, before the first frame.
public void setClearColor(int argb)Sets the ARGB color the view is cleared to each frame.
public void start()Starts the game loop (continuous rendering).
public void stop()Stops the game loop (no further frames until #start()).
public void pause()Pauses updates; frames still render but #update(double) is not called.
public void resume()Resumes after #pause().
public boolean isRunning()
public boolean isPaused()
public void setFixedTimestep(double seconds)Sets a fixed update interval in seconds (0 disables, the default).
public double getFixedTimestep()
public double getInterpolationAlpha()The 0..1 fraction of a fixed step left after the last update, for interpolating rendered positions.
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.
protected void deinitialize()Invoked to indicate that the component initialization is being reversed since the component was detached from the container hierarchy.
public void frame(double deltaSeconds)Invoked every frame before the scene is drawn.
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.
public void keyPressed(int keyCode)If this Component is focused, the key pressed event will call this method
public void keyReleased(int keyCode)If this Component is focused, the key released event will call this method
public void pointerPressed(int[] x, int[] y)If this Component is focused, the pointer pressed event will call this method
public void pointerDragged(int[] x, int[] y)If this Component is focused, the pointer dragged event will call this method
public void pointerReleased(int[] x, int[] y)If this Component is focused, the pointer released event will call this method

Inherited fields

Inherited methods

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

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

public Scene getScene()
The scene drawn by this view; add and remove Sprites here.

getInput

public GameInput getInput()
The pollable input state for this view.

getControls

public TouchControls 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 same GameInput your keyboard handling already reads.

getCamera

public GameCamera getCamera()
The camera this view renders through. It starts in 2D mode; call GameCamera#setPerspective(float, float, float) on it to switch the view into a 3D perspective with billboarded sprites.

getLight

public Light getLight()
The directional light shading lit 3D Models in perspective mode.

addModel

public void addModel(Model model)
Adds a 3D Model to be drawn in the perspective camera alongside the sprites. Build models from #onSetup(com.codename1.gpu.GraphicsDevice), where the GPU device is available.

removeModel

public void removeModel(Model model)
Removes a previously added 3D Model.

onSetup

protected void onSetup(GraphicsDevice device)
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 call com.codename1.gpu.Primitives / com.codename1.gpu.GltfLoader, which need the device. The default does nothing.

Parameters

device GraphicsDevice
the GPU device for creating meshes, textures and buffers

setup

public void setup(GraphicsDevice device)
Invoked once after the GPU device is created, before the first frame. 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.

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.

frame

public void frame(double deltaSeconds)
Invoked every frame before the scene is drawn. Drives game logic each frame – invoked by the SpriteRenderer before 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.

Returns

true if key events are being used for focus traversal ; otherwise false

keyPressed

public void keyPressed(int keyCode)
If this Component is focused, the key pressed event will call this method

Parameters

keyCode int
the key code value to indicate a physical key.

keyReleased

public void keyReleased(int keyCode)
If this Component is focused, the key released event will call this method

Parameters

keyCode int
the key code value to indicate a physical key.

pointerPressed

public void pointerPressed(int[] x, int[] y)
If this Component is focused, the pointer pressed event will call this method

Parameters

x int[]
the pointer x coordinate
y int[]
the pointer y coordinate

pointerDragged

public void pointerDragged(int[] x, int[] y)
If this Component is focused, the pointer dragged event will call this method

Parameters

x int[]
the pointer x coordinate
y int[]
the pointer y coordinate

pointerReleased

public void pointerReleased(int[] x, int[] y)
If this Component is focused, the pointer released event will call this method

Parameters

x int[]
the pointer x coordinate
y int[]
the pointer y coordinate