Client API. The Codename One framework your app is built on: this runs on the device, not in a backend.

public class PlatformView

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

ImplementsAnimation, Editable, Iterable<Component>, StyleListener

Plays a PlatformWorld on screen: steps it at a fixed 60 Hz from the player’s input, draws it through a PlatformArt, follows the player with a GameCamera’s follow mode and plays each tick’s events through Feedback.

import com.codename1.gaming.platformer.*;
import com.codename1.gaming.platformer.view.*;

LevelData level = LevelData.parse("{\"tileSize\":16,\"spawn\":[1,1],\"tiles\":[\"........\",\"........\",\"########\"]}");
PlatformWorld world = level.createWorld(1);
Form form = new Form("Level", new BorderLayout());
PlatformView view = new PlatformView(world, new ProceduralArt(level.getTileSize()));
form.add(BorderLayout.CENTER, view);
form.show();
view.start();

Drawing is interpolated between the last two ticks, so motion is smooth at any display rate while the simulation stays exactly 60 Hz. Tiles are baked into chunk images once and re-baked only where the grid changes. Positions are in world pixels multiplied by a scale chosen so #setVisibleRows rows of tiles fill the height of the view.

#setDepth(boolean) turns on 2.5D: the same world, the same rules and the same replay, drawn with a perspective camera. Solid ground becomes extruded blocks and actors, entities and backdrops become billboards at depth, so backdrops get real parallax. The simulation cannot tell the difference.

Override #onEvent for game rules the view should react to (a HUD, a win screen), or set an InputSource to drive the world from a replay or a network peer instead of the local player.

Nested types

interface PlatformView.InputSourceSupplies the player’s input instead of the device, for a replay or a remote player.

Constructors

public PlatformView(PlatformWorld world, PlatformArt art)Creates a view.

Methods

public final void setWorld(PlatformWorld world, PlatformArt art)Replaces the world, as when the next level starts or a level restarts.
public void setDepth(boolean depth)Draws in 2.5D: a perspective camera over extruded blocks and billboard sprites.
public boolean isDepth()Whether the view draws in 2.5D.
public void setDepthLook(float fovDegrees, float tilt, float blockDepth)Tunes the 2.5D look.
public void setDepthTextures(Image solid, Image ledge, Image hazard, Image ladder)Textures the depth mode’s blocks with tile art instead of flat colour.
public void setDepthColors(int solid, int ledge, int hazard, int ladder)The 2.5D block colors.
protected void onSetup(GraphicsDevice device)Override to allocate GPU resources (meshes, textures, Models) once the GPU device is ready.
public void addBackground(Image image, float factor, double y)Adds a parallax backdrop behind the level, repeated across the view.
public void setArtScale(double scale)How many art pixels the PlatformArt draws per world pixel.
public void refreshTiles()Draws every tile again from the art on the next frame.
public double getArtScale()Art pixels per world pixel.
public void setVisibleRows(double rows)How many rows of tiles fill the view’s height; sets the scale.
public void setMinVisibleColumns(double cols)Keeps at least this many tile columns in view, so a narrow screen (a phone held upright) zooms out instead of hiding what is ahead.
public void setPlayerMappers(InputMapper... mappers)Reads one mapper per player, for a shared-screen game (PlatformWorld#setPlayerCount(int)): each tick player i gets what mappers[i] reads, typically InputMapper#forPlayer(int).
public int[] getPlayerInputs()What each player’s mapper read this tick.
public void setModels(PlatformModels models)Draws actors as 3D models in depth mode.
public void setZoom(double zoom)Zooms the view: 2 shows half as much at twice the size.
public double getZoom()The zoom set by setZoom.
public void setFrameAllPlayers(boolean all)Whether, with more than one player (PlatformWorld.setPlayerCount), the camera frames all of them and zooms out as they spread.
public Feedback getFeedback()The feedback, to change what events look and sound like.
public void setFeedback(Feedback feedback)Replaces the feedback.
public void setFeedbackSink(Feedback.Sink sink)Receives the sounds and particle bursts of the feedback.
public InputMapper getInputMapper()The input mapper, to remap keys.
public void setInputMapper(InputMapper mapper)Replaces the input mapper.
public void setInputSource(PlatformView.InputSource source)Drives the world from somewhere other than the local devices.
public PlatformWorld getWorld()The world being played.
public PlatformArt getArt()The art the view draws with.
public int getLastInput()The Input bits the local devices produced on the last tick, for a recorder.
protected void update(double deltaSeconds)Advance the game by the given amount of time.
protected void onTick(int localInput)Called after every tick, before the events are played.
protected void onEvent(WorldEvent e)Called for every event of every tick, after its feedback played.
public void addGhost(PlatformWorld ghostWorld, int[] inputs, int alpha)Races a recorded run alongside this one: ghostWorld is stepped with inputs on every tick the live world steps, and its hero is drawn translucent.
public void clearGhosts()Removes every ghost.
public List<PlatformWorld> getGhostWorlds()The ghosts’ worlds, in the order they were added, so a HUD can say who is ahead.
public void frame(double deltaSeconds)Positions everything for this frame, between the last two ticks.
protected Image createParticleImage()The image a particle is drawn with: a soft white dot, tinted per burst.

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, 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, 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, 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, getContextMenuCommands, setContextMenuCommands, mouseWheel, paintRippleOverlay, removePointerPressedListener, removeLongPressListener, removeDragFinishedListener, addPointerReleasedListener, removePointerReleasedListener, addPointerDraggedListener, removePointerDraggedListener, getDragSpeed, getStyle, getPressedStyle, getHoverStyle, setHoverStyle, isHovered, setHovered, 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

PlatformView

public PlatformView(PlatformWorld world, PlatformArt art)
Creates a view.

Parameters

world PlatformWorld
the world to play
art PlatformArt
draws it

Method details

setWorld

public final void setWorld(PlatformWorld world, PlatformArt art)
Replaces the world, as when the next level starts or a level restarts.

Parameters

world PlatformWorld
the new world
art PlatformArt
draws it

setDepth

public void setDepth(boolean depth)
Draws in 2.5D: a perspective camera over extruded blocks and billboard sprites. Call before #start() or at any time after.

Parameters

depth boolean
true for 2.5D, false for flat 2D

isDepth

public boolean isDepth()
Whether the view draws in 2.5D.

Returns

true in 2.5D

setDepthLook

public void setDepthLook(float fovDegrees, float tilt, float blockDepth)
Tunes the 2.5D look.

Parameters

fovDegrees float
the vertical field of view, 40 by default
tilt float
how far above the action the camera sits, as a fraction of its distance; 0.18 by default
blockDepth float
how deep solid ground extrudes, in tiles; 1.6 by default

setDepthTextures

public void setDepthTextures(Image solid, Image ledge, Image hazard, Image ladder)
Textures the depth mode’s blocks with tile art instead of flat colour. Every face of a block shows the whole image, so a tile with grass along its top reads as a grassy block from the front and the side. Any argument may be null to keep that kind’s colour. Call before the view starts.

Parameters

solid Image
solid ground and slopes
ledge Image
one-way ledges
hazard Image
spikes
ladder Image
ladders

setDepthColors

public void setDepthColors(int solid, int ledge, int hazard, int ladder)
The 2.5D block colors.

Parameters

solid int
ground and slopes
ledge int
one-way ledges
hazard int
spikes
ladder int
ladders

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

addBackground

public void addBackground(Image image, float factor, double y)
Adds a parallax backdrop behind the level, repeated across the view.

Parameters

image Image
the layer
factor float
how much it scrolls with the world; 0 pinned, 1 with the level
y double
its top in world pixels

setArtScale

public void setArtScale(double scale)
How many art pixels the PlatformArt draws per world pixel. A level with 16 pixel tiles and art drawn at 64 pixels a tile uses 4: tiles, sprites and backdrops are then drawn at their full resolution instead of being scaled up from the level’s own pixel size. Call before #start().

Parameters

scale double
art pixels per world pixel, 1 by default

refreshTiles

public void refreshTiles()
Draws every tile again from the art on the next frame. Call it when the art changes what a tile looks like – a new palette, a new tileset – since the view keeps the tiles it has drawn.

getArtScale

public double getArtScale()
Art pixels per world pixel.

Returns

the art scale

setVisibleRows

public void setVisibleRows(double rows)
How many rows of tiles fill the view’s height; sets the scale.

Parameters

rows double
rows, 12 by default

setMinVisibleColumns

public void setMinVisibleColumns(double cols)
Keeps at least this many tile columns in view, so a narrow screen (a phone held upright) zooms out instead of hiding what is ahead. The view shows setVisibleRows rows or this many columns, whichever needs the smaller tiles. 0, the default, fits rows only.

Parameters

cols double
columns, or 0

setPlayerMappers

public void setPlayerMappers(InputMapper... mappers)
Reads one mapper per player, for a shared-screen game (PlatformWorld#setPlayerCount(int)): each tick player i gets what mappers[i] reads, typically InputMapper#forPlayer(int). An InputSource, when set, still has the last word: it receives player one’s bits as local and can read the rest from getPlayerInputs().

Parameters

mappers InputMapper...
one per player, or null for a single player

getPlayerInputs

public int[] getPlayerInputs()
What each player’s mapper read this tick.

Returns

the live array, or null without setPlayerMappers

setModels

public void setModels(PlatformModels models)
Draws actors as 3D models in depth mode. See PlatformModels.

Parameters

models PlatformModels
the models, or null for billboards

setZoom

public void setZoom(double zoom)
Zooms the view: 2 shows half as much at twice the size. The change is eased over a few frames.

Parameters

zoom double
above 0

getZoom

public double getZoom()
The zoom set by setZoom.

Returns

the zoom

setFrameAllPlayers

public void setFrameAllPlayers(boolean all)
Whether, with more than one player (PlatformWorld.setPlayerCount), the camera frames all of them and zooms out as they spread. On by default; off follows the first player only.

Parameters

all boolean
true to frame every player

getFeedback

public Feedback getFeedback()
The feedback, to change what events look and sound like.

Returns

the feedback

setFeedback

public void setFeedback(Feedback feedback)
Replaces the feedback.

Parameters

feedback Feedback
the feedback

setFeedbackSink

public void setFeedbackSink(Feedback.Sink sink)
Receives the sounds and particle bursts of the feedback.

Parameters

sink Feedback.Sink
the sink, may be null

getInputMapper

public InputMapper getInputMapper()
The input mapper, to remap keys.

Returns

the mapper

setInputMapper

public void setInputMapper(InputMapper mapper)
Replaces the input mapper.

Parameters

mapper InputMapper
the mapper

setInputSource

public void setInputSource(PlatformView.InputSource source)
Drives the world from somewhere other than the local devices.

Parameters

source PlatformView.InputSource
the source, or null for the local player

getWorld

public PlatformWorld getWorld()
The world being played.

Returns

the world

getArt

public PlatformArt getArt()
The art the view draws with.

Returns

the art

getLastInput

public int getLastInput()
The Input bits the local devices produced on the last tick, for a recorder.

Returns

the bits

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

onTick

protected void onTick(int localInput)
Called after every tick, before the events are played.

Parameters

localInput int
what the local devices read

onEvent

protected void onEvent(WorldEvent e)
Called for every event of every tick, after its feedback played.

Parameters

e WorldEvent
the event

addGhost

public void addGhost(PlatformWorld ghostWorld, int[] inputs, int alpha)
Races a recorded run alongside this one: ghostWorld is stepped with inputs on every tick the live world steps, and its hero is drawn translucent. Nothing it does reaches the live world, the feedback or the events – it is a picture of another run, which is exactly what a replayed log reproduces. Build ghostWorld from the same level and seed the run was recorded with, and add it before the first tick.

Parameters

ghostWorld PlatformWorld
a fresh world for the ghost
inputs int[]
its input for every tick, as InputLog.toArray gives it
alpha int
how opaque to draw it, 0 to 255

clearGhosts

public void clearGhosts()
Removes every ghost.

getGhostWorlds

public List<PlatformWorld> getGhostWorlds()
The ghosts’ worlds, in the order they were added, so a HUD can say who is ahead.

Returns

a new list

frame

public void frame(double deltaSeconds)
Positions everything for this frame, between the last two ticks.

createParticleImage

protected Image createParticleImage()
The image a particle is drawn with: a soft white dot, tinted per burst. Override for sparks, leaves or embers.

Returns

the particle image