Client API. The Codename One framework your app is built on: this runs on the device, not in a backend.
public class PlatformView
- Object
- Component
- Container
- RenderView
- GameView
- 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.InputSource | Supplies 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
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, getEnvironment, setPostProcess, addModel, removeModel, releaseTexture, getTextureCount, setClearColor, start, stop, pause, resume, isRunning, isPaused, setFixedTimestep, getFixedTimestep, getInterpolationAlpha, initComponent, deinitialize, handlesInput, keyPressed, keyReleased, keyRepeated, pointerPressed, pointerReleased, 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, 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
From Iterable
Constructor details
PlatformView
public PlatformView(PlatformWorld world, PlatformArt art)Parameters
worldPlatformWorld- the world to play
artPlatformArt- draws it
Method details
setWorld
public final void setWorld(PlatformWorld world, PlatformArt art)Parameters
worldPlatformWorld- the new world
artPlatformArt- draws it
setDepth
public void setDepth(boolean depth)#start() or at any time after.Parameters
depthboolean- true for 2.5D, false for flat 2D
isDepth
public boolean isDepth()Returns
setDepthLook
public void setDepthLook(float fovDegrees, float tilt, float blockDepth)Parameters
fovDegreesfloat- the vertical field of view, 40 by default
tiltfloat- how far above the action the camera sits, as a fraction of its distance; 0.18 by default
blockDepthfloat- how deep solid ground extrudes, in tiles; 1.6 by default
setDepthTextures
public void setDepthTextures(Image solid, Image ledge, Image hazard, Image ladder)Parameters
solidImage- solid ground and slopes
ledgeImage- one-way ledges
hazardImage- spikes
ladderImage- ladders
setDepthColors
public void setDepthColors(int solid, int ledge, int hazard, int ladder)Parameters
solidint- ground and slopes
ledgeint- one-way ledges
hazardint- spikes
ladderint- ladders
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.Parameters
deviceGraphicsDevice- the GPU device for creating meshes, textures and buffers
addBackground
public void addBackground(Image image, float factor, double y)Parameters
imageImage- the layer
factorfloat- how much it scrolls with the world; 0 pinned, 1 with the level
ydouble- its top in world pixels
setArtScale
public void setArtScale(double scale)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
scaledouble- art pixels per world pixel, 1 by default
refreshTiles
public void refreshTiles()getArtScale
public double getArtScale()Returns
setVisibleRows
public void setVisibleRows(double rows)Parameters
rowsdouble- rows, 12 by default
setMinVisibleColumns
public void setMinVisibleColumns(double cols)setVisibleRows rows or this many columns, whichever needs
the smaller tiles. 0, the default, fits rows only.Parameters
colsdouble- columns, or 0
setPlayerMappers
public void setPlayerMappers(InputMapper... mappers)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
mappersInputMapper...- one per player, or null for a single player
getPlayerInputs
public int[] getPlayerInputs()Returns
setPlayerMapperssetModels
public void setModels(PlatformModels models)PlatformModels.Parameters
modelsPlatformModels- the models, or null for billboards
setZoom
public void setZoom(double zoom)Parameters
zoomdouble- above 0
getZoom
public double getZoom()setZoom.Returns
setFrameAllPlayers
public void setFrameAllPlayers(boolean all)PlatformWorld.setPlayerCount),
the camera frames all of them and zooms out as they spread. On by
default; off follows the first player only.Parameters
allboolean- true to frame every player
getFeedback
public Feedback getFeedback()Returns
setFeedback
public void setFeedback(Feedback feedback)Parameters
feedbackFeedback- the feedback
setFeedbackSink
public void setFeedbackSink(Feedback.Sink sink)Parameters
sinkFeedback.Sink- the sink, may be null
getInputMapper
public InputMapper getInputMapper()Returns
setInputMapper
public void setInputMapper(InputMapper mapper)Parameters
mapperInputMapper- the mapper
setInputSource
public void setInputSource(PlatformView.InputSource source)Parameters
sourcePlatformView.InputSource- the source, or null for the local player
getWorld
public PlatformWorld getWorld()Returns
getArt
public PlatformArt getArt()Returns
getLastInput
public int getLastInput()Input bits the local devices produced on the last tick, for a
recorder.Returns
update
protected void update(double deltaSeconds)#setFixedTimestep(double) is used).onTick
protected void onTick(int localInput)Parameters
localInputint- what the local devices read
onEvent
protected void onEvent(WorldEvent e)Parameters
eWorldEvent- the event
addGhost
public void addGhost(PlatformWorld ghostWorld, int[] inputs, int alpha)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
ghostWorldPlatformWorld- a fresh world for the ghost
inputsint[]- its input for every tick, as
InputLog.toArraygives it alphaint- how opaque to draw it, 0 to 255
clearGhosts
public void clearGhosts()getGhostWorlds
public List<PlatformWorld> getGhostWorlds()Returns
frame
public void frame(double deltaSeconds)createParticleImage
protected Image createParticleImage()