Class PlatformView
- All Implemented Interfaces:
Animation, Editable, StyleListener, Iterable<Component>
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 Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic interfaceSupplies the player's input instead of the device, for a replay or a remote player. -
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 TypeMethodDescriptionvoidaddBackground(Image image, float factor, double y) Adds a parallax backdrop behind the level, repeated across the view.voidaddGhost(PlatformWorld ghostWorld, int[] inputs, int alpha) Races a recorded run alongside this one:ghostWorldis stepped withinputson every tick the live world steps, and its hero is drawn translucent.voidRemoves every ghost.protected ImageThe image a particle is drawn with: a soft white dot, tinted per burst.voidframe(double deltaSeconds) Positions everything for this frame, between the last two ticks.getArt()The art the view draws with.doubleArt pixels per world pixel.The feedback, to change what events look and sound like.The ghosts' worlds, in the order they were added, so a HUD can say who is ahead.The input mapper, to remap keys.intTheInputbits the local devices produced on the last tick, for a recorder.int[]What each player's mapper read this tick.getWorld()The world being played.doublegetZoom()The zoom set bysetZoom.booleanisDepth()Whether the view draws in 2.5D.protected voidCalled for every event of every tick, after its feedback played.protected voidonSetup(GraphicsDevice device) Override to allocate GPU resources (meshes, textures,Models) once the GPU device is ready.protected voidonTick(int localInput) Called after every tick, before the events are played.voidDraws every tile again from the art on the next frame.voidsetArtScale(double scale) How many art pixels thePlatformArtdraws per world pixel.voidsetDepth(boolean depth) Draws in 2.5D: a perspective camera over extruded blocks and billboard sprites.voidsetDepthColors(int solid, int ledge, int hazard, int ladder) The 2.5D block colors.voidsetDepthLook(float fovDegrees, float tilt, float blockDepth) Tunes the 2.5D look.voidsetDepthTextures(Image solid, Image ledge, Image hazard, Image ladder) Textures the depth mode's blocks with tile art instead of flat colour.voidsetFeedback(Feedback feedback) Replaces the feedback.voidsetFeedbackSink(Feedback.Sink sink) Receives the sounds and particle bursts of the feedback.voidsetFrameAllPlayers(boolean all) Whether, with more than one player (PlatformWorld.setPlayerCount), the camera frames all of them and zooms out as they spread.voidsetInputMapper(InputMapper mapper) Replaces the input mapper.voidDrives the world from somewhere other than the local devices.voidsetMinVisibleColumns(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.voidsetModels(PlatformModels models) Draws actors as 3D models in depth mode.voidsetPlayerMappers(InputMapper... mappers) Reads one mapper per player, for a shared-screen game (PlatformWorld#setPlayerCount(int)): each tick playerigets whatmappers[i]reads, typicallyInputMapper#forPlayer(int). AnInputSource, when set, still has the last word: it receives player one's bits aslocaland can read the rest fromgetPlayerInputs().voidsetVisibleRows(double rows) How many rows of tiles fill the view's height; sets the scale.final voidsetWorld(PlatformWorld world, PlatformArt art) Replaces the world, as when the next level starts or a level restarts.voidsetZoom(double zoom) Zooms the view: 2 shows half as much at twice the size.protected voidupdate(double deltaSeconds) Advance the game by the given amount of time.Methods inherited from class GameView
addModel, deinitialize, getCamera, getControls, getEnvironment, getFixedTimestep, getInput, getInterpolationAlpha, getLight, getScene, getTextureCount, handlesInput, initComponent, isPaused, isRunning, keyPressed, keyReleased, keyRepeated, pause, pointerDragged, pointerPressed, pointerPressed, pointerReleased, pointerReleased, releaseTexture, removeModel, resume, setClearColor, setFixedTimestep, setPostProcess, 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, 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
accessibilityChanged, accessibilityChanged, addContextMenuListener, addDragFinishedListener, addDragOverListener, addDropListener, addFocusListener, addLongPressListener, addMouseWheelListener, addNativeDragOverListener, addNativeDropListener, addPointerDraggedListener, addPointerPressedListener, addPointerReleasedListener, addPullToRefresh, addScrollListener, addStateChangeListener, addStylusListener, animate, announceForAccessibility, bindProperty, blocksSideSwipe, calcScrollSize, canAcceptNativeDrop, consumesRawTextInput, contains, containsOrOwns, createNativeDragOperation, createStyleAnimation, deinitializeCustomStyle, deregisterFromAnimation, dragEnter, dragExit, dragFinished, draggingOver, drawDraggedImage, focusGained, focusLost, getAbsoluteX, getAbsoluteY, getAcceptedDropActions, getAcceptedDropMimeTypes, getAccessibilityNode, getAccessibilityText, getAllStyles, getAnimationManager, getBaseline, getBaselineResizeBehavior, getBindablePropertyNames, getBindablePropertyTypes, getBorder, getBoundPropertyValue, getBounds, getBounds, getClientProperty, getCloudBoundProperty, getCloudDestinationProperty, getComponentForm, getComponentState, getContextMenuCommands, getCursor, getDefaultDragTransparency, getDirtyRegion, getDisabledStyle, getDraggedx, getDraggedy, getDragImage, getDragRegionStatus, getDragSpeed, getDragTransparency, getEditingDelegate, getHeight, getHoverStyle, getInlineAllStyles, getInlineDisabledStyles, getInlinePressedStyles, getInlineSelectedStyles, getInlineStylesTheme, getInlineUnselectedStyles, getInnerHeight, getInnerPreferredH, getInnerPreferredW, getInnerWidth, getInnerX, getInnerY, getLabelForComponent, getName, getNativeDragOperation, 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, getSemantics, getStyle, getTabIndex, getTensileLength, getTextSelectionSupport, getTooltip, getTopLevelContainer, 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, isHovered, isHScrollThumbGrabbed, isHScrollThumbHover, isIgnorePointerEvents, isInClippingRegion, isInitialized, isNativeDragSource, isNativeDropTarget, isOpaque, isOwnedBy, isPinchBlocksDragAndDrop, isRippleEffect, isRTL, isScrollable, isScrollVisible, isSetCursorSupported, isSmoothScrolling, isSnapToGrid, isStickyDrag, isTactileTouch, isTactileTouch, isTensileDragEnabled, isTraversable, isVisible, isVScrollThumbGrabbed, isVScrollThumbHover, laidOut, longKeyPress, longPointerPress, mouseWheel, nativeDragEnter, nativeDragExit, nativeDragOver, nativeDrop, 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, putClientProperty, refreshTheme, refreshTheme, registerForAnimation, remove, removeContextMenuListener, removeDragFinishedListener, removeDragOverListener, removeDropListener, removeFocusListener, removeLongPressListener, removeMouseWheelListener, removeNativeDragOverListener, removeNativeDropListener, removePointerDraggedListener, removePointerPressedListener, removePointerReleasedListener, removeScrollListener, removeStateChangeListener, removeStylusListener, repaint, repaint, requestFocus, resetFocusable, respondsToPointerEvents, rotation, scrollRectToVisible, scrollRectToVisible, setAcceptedDropActions, setAcceptedDropMimeTypes, setAccessibilityText, setAlwaysTensile, setBlockLead, setBoundPropertyValue, setCloudBoundProperty, setCloudDestinationProperty, setComponentState, setContextMenuCommands, setCursor, setDefaultDragTransparency, setDirtyRegion, setDisabledStyle, setDraggable, setDragTransparency, setDropTarget, setEditingDelegate, setFlatten, setFocus, setFocusable, setGrabsPointerEvents, setHandlesInput, setHeight, setHidden, setHidden, setHideInLandscape, setHideInPortrait, setHorizontalScrollBounds, setHovered, setHoverStyle, setIgnorePointerEvents, setInitialized, setInlineAllStyles, setInlineDisabledStyles, setInlinePressedStyles, setInlineSelectedStyles, setInlineStylesTheme, setInlineUnselectedStyles, setIsScrollVisible, setLabelForComponent, setName, setNativeDragOperation, setNativeDragSource, setNativeDropTarget, 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, stopScrollMomentum, stripMarginAndPadding, styleChanged, toImage, toString, unbindProperty, updateNativeOverlay, visibleBoundsContainsMethods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods inherited from interface Iterable
forEach, spliterator
-
Constructor Details
-
PlatformView
Creates a view.
Parameters
world: the world to playart: draws it
-
-
Method Details
-
setWorld
Replaces the world, as when the next level starts or a level restarts.
Parameters
world: the new worldart: 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: 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: the vertical field of view, 40 by defaulttilt: how far above the action the camera sits, as a fraction of its distance; 0.18 by defaultblockDepth: how deep solid ground extrudes, in tiles; 1.6 by default
-
setDepthTextures
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: solid ground and slopesledge: one-way ledgeshazard: spikesladder: ladders
-
setDepthColors
public void setDepthColors(int solid, int ledge, int hazard, int ladder) The 2.5D block colors.
Parameters
solid: ground and slopesledge: one-way ledgeshazard: spikesladder: ladders
-
onSetup
Description copied from class:GameViewOverride 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
-
addBackground
Adds a parallax backdrop behind the level, repeated across the view.
Parameters
image: the layerfactor: how much it scrolls with the world; 0 pinned, 1 with the levely: its top in world pixels
-
setArtScale
public void setArtScale(double scale) How many art pixels the
PlatformArtdraws 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: 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: 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
setVisibleRowsrows or this many columns, whichever needs the smaller tiles. 0, the default, fits rows only.Parameters
cols: columns, or 0
-
setPlayerMappers
Reads one mapper per player, for a shared-screen game (
PlatformWorld#setPlayerCount(int)): each tick playerigets whatmappers[i]reads, typicallyInputMapper#forPlayer(int). AnInputSource, when set, still has the last word: it receives player one's bits aslocaland can read the rest fromgetPlayerInputs().Parameters
mappers: 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
Draws actors as 3D models in depth mode. See
PlatformModels.Parameters
models: 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: 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: true to frame every player
-
getFeedback
The feedback, to change what events look and sound like.
Returns
the feedback
-
setFeedback
Replaces the feedback.
Parameters
feedback: the feedback
-
setFeedbackSink
Receives the sounds and particle bursts of the feedback.
Parameters
sink: the sink, may be null
-
getInputMapper
The input mapper, to remap keys.
Returns
the mapper
-
setInputMapper
Replaces the input mapper.
Parameters
mapper: the mapper
-
setInputSource
Drives the world from somewhere other than the local devices.
Parameters
source: the source, or null for the local player
-
getWorld
The world being played.
Returns
the world
-
getArt
The art the view draws with.
Returns
the art
-
getLastInput
public int getLastInput()The
Inputbits the local devices produced on the last tick, for a recorder.Returns
the bits
-
update
-
onTick
protected void onTick(int localInput) Called after every tick, before the events are played.
Parameters
localInput: what the local devices read
-
onEvent
Called for every event of every tick, after its feedback played.
Parameters
e: the event
-
addGhost
Races a recorded run alongside this one:
ghostWorldis stepped withinputson 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. BuildghostWorldfrom the same level and seed the run was recorded with, and add it before the first tick.Parameters
ghostWorld: a fresh world for the ghostinputs: its input for every tick, asInputLog.toArraygives italpha: how opaque to draw it, 0 to 255
-
clearGhosts
public void clearGhosts()Removes every ghost. -
getGhostWorlds
The ghosts' worlds, in the order they were added, so a HUD can say who is ahead.
Returns
a new list
-
frame
-
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
-