FlatRedBall
  • 🖥️Downloading FlatRedBall
  • 🏗️Building FlatRedBall From Source
    • Linking Games to FlatRedBall Engine Source
    • Linking FNA
  • ❓Need Help?
  • ✨FlatRedBall Features
  • 🎓Tutorials
    • Introduction To FlatRedBall
    • Quick Start Guide
    • Beefball - A Full FlatRedBall Tutorial Project
      • Creating a FlatRedBall Project
      • Creating an Entity
      • Creating a Screen
      • Controlling an Entity
      • Creating the Screen Collision
      • Advanced PlayerBall Controls
      • Creating the Puck Entity
      • Adding Multiple Players
      • Scoring and Restarting Rounds
      • Scoring Hud
      • Scoring Hud Logic
      • Adding Dashing
    • Platformer Tutorials
      • Platformer Basics
        • Creating an Entity
        • Controlling a Platformer Entity
        • Movement Values
        • Double Jump
      • Checkpoint and Level End
      • Climbing Ladders
      • Doors
      • GroundCollidedAgainst and Movement Values
      • Moving Platforms
      • Multiple Players
      • NPC Dialog
      • Breaking Blocks
        • New Project Setup
        • Creating Level1 Map
        • Creating the Block Entity
        • Block Removal
      • Dealing Damage
        • New Project Setup
        • Enemy Entity
        • Shooting Bullets
        • Damaging the Enemy
      • Enemy Movement
        • New Project Setup
        • Enemy Entity
        • Enemy Input Logic
        • Detecting Platform Edges
      • Ground Type and Water Movement
        • New Project Setup
        • Creating Level1 Map
        • Adding Ice and Water
        • Platformer Movement Values
      • Animation and Platformer Values
        • New Project Setup
        • Creating AnimationLayers
        • Modifying Platformer Values
      • Wall Sliding and Jumping
    • Damage Dealing
      • Setup
      • Team Index
      • Damage Events
      • IDamageArea Removal
      • Melee Damage
    • Entity Variants Using Inheritance
    • FlatRedBall.Forms
      • Getting Started with FlatRedBall.Forms
        • Setup
        • Working with Common Controls
        • Forms vs Gum in Code
      • Forms and Xbox360GamePad
      • Data Binding (BindingContext)
        • BindingContext Property
        • Binding FlatRedBall.Forms
        • Parent and Children Binding using BindingContext
        • ListBox Templates
      • Styling Forms
      • Defining New Forms Types
        • Adding New Types to FlatRedBall.Forms Library
      • Accessing Forms Events in Gum Runtimes
    • Top Down Games
      • Top Down Basics
        • Setup
        • Input Device
        • CurrentMovement
      • Enemy Movement
        • Enemy Pathfinding
        • Direct Enemy Control
      • GroundVelocity
      • Animation
      • Sorting
    • Post Processing
    • Rock Blaster - A Full FlatRedBall Tutorial Project
      • Introduction
      • Setup
      • Game Skeleton
      • Player Entity
      • Player Behavior
      • Rock Entity
      • Collision
      • Rock States
      • HUD
      • Multiple Players
      • Health
      • Health Part 2
      • Destroying Entities
      • Cleaning Up
    • Code-Only Projects (No Editor)
      • Creating a FlatRedBall Project
      • Adding a Circle
      • Loading Textures and Using Sprites
    • Code Tutorials
      • 3D Camera Setup
      • Adding FlatRedBall to a MonoGame/FNA Project
      • Adding WPF to an Existing Game
      • async and await
      • CLR Profiler
      • Collision Jitter
      • Culling
      • Customizing Cursor Visuals
        • Windows Desktop
        • windows-rt
      • Depth Buffer Z Fighting
      • Dictionaries and Enum Keys
      • FlatRedBall XNA in Windows Form
      • Improving Performance
        • CustomActivity Performance
        • Identifying Screen Creation Performance Issues
        • Rendering Performance
        • Manually Updated Objects
          • Introduction
          • Measuring Automatic Updates
          • Measuring Sprite Automatic Updates
          • Manual Particle Systems
      • Object Sorting
      • Pix
      • Rendering Sprites with Shaders
      • Tile-Based Movement
      • Velocity
    • Distribution
      • App Icon
      • Emptying bin Folder Using Probing Path
      • itch.io
      • Release Build
      • Steam
    • FlatRedBall and Velcro Physics
      • Using Velcro Physics with the FlatRedBall Editor
      • Code-Only Velcro Projects
    • FlatRedBall Editor Plugins
      • Introduction to FlatRedBall Plugins
      • Creating a Plugin Project
      • Creating a Plugin Class
      • Adding UI to FlatRedBall
      • Using MVVM
      • Creating a NamedObjectSave-Editing Plugin
      • Adding File Format Support
      • Adding Code Files to a Game Project
      • Errors
      • Exporting a Plugin
    • Additional FlatRedBall Editor Tutorials
      • How to Create a First Person Camera
      • How to Play Sounds
      • How to Share Reference Data Between Screens and Entities
    • Math Tutorials
      • Circle Collision
      • Determining required magnitude for trajectory
      • Introduction to Collision
      • Power of Two
      • Rectangle Collision
      • rotation
      • statistics
      • trigonometry
      • vector
      • matrix
      • interpolation
    • Overworld Tutorials
      • Spinning Mode 7
        • New Project Setup
        • Adding Camera Code
        • Fading In and Out
  • 🎞️Videos
  • 📐FlatRedBall Editor
    • Display Settings
    • Entities
      • BaseEntity
      • Constructor
      • ConvertToManuallyUpdated
      • CreatedByOtherEntities
      • CustomActivity
      • CustomDestroy
      • CustomInitialize
      • Destroying Entities
      • Entity Performance
      • Export Entity
      • Implements IClickable
      • Implements ICollidable
      • Implements IDamageArea
      • Implements IDrawableBatch
      • Implements IGumCollidable
      • Implements IVisible
      • Implements IWindow
        • SlideOnClick
      • Import Entity
      • Inheriting from FlatRedBall Types
      • LayerProvidedByContainer
      • MoveToLayer
      • PooledByFactory
      • Top Down Movement
        • TopDownSpeedMultiplier
      • Use Global Content
    • Events
      • ResolutionRrOrientationChanged
    • Factories
      • CreateNew
      • EntitySpawned
      • Initialize
      • SortAxis
    • Files
      • File Types
        • Animation Chain List (.achx)
        • Comma Separated Values (.csv)
          • Combining .csvs With Entities
          • CreatesDictionary
          • Cross Referencing CSVs
          • Instantiating Custom Types
          • OrderedList
          • SetCreatedClass
            • generate-data-class
          • uniformrowtype
        • Effect (.fx, .fxb)
        • Font (.fnt)
        • JSON (.json)
        • Model (.fbx)
        • MP3
        • Node Network (.nntx)
        • OpenDocument Spreadsheet (.ods)
        • ShapeCollections (.shcx)
        • SplineList (.splx)
        • Texture2D (.png)
        • Wave (.wav)
      • Accessing Files in Code
      • Adding File Objects to Managers
      • Destroy on Unload
      • File Build Tool
      • Folders
      • Global Content Files
      • IsDatabaseForLocalizing
      • IsManuallyUpdated
      • IncludeDirectoryRelativeToContainer
      • LoadedAtRuntime
      • LoadedOnlyWhenReferenced
      • Name
      • Platform Inclusions
      • Project Specific Files
      • RuntimeType
      • SourceFile
      • UseContentPipeline
      • Wildcard Files
    • FileVersion (.gluj)
    • Generated Code
    • Global Content Files
      • LoadAsynchronously
      • Reload
      • Setting Files At Runtime
    • Live Edit
      • Render Targets
    • Menu
      • Content
        • Additional Content
          • Using Runtime Types as Objects
          • creating-runtime-objects
          • runtime-object-charateristics
          • simple-line-of-text-tutorial
        • Introduction
        • pipeline-settings
      • File
        • New Project
      • Edit
        • Find File References
      • Plugins
        • Install Plugin
        • Manage Plugins
      • Project
        • View Projects
      • Settings
        • Camera Settings
        • File Associations
        • File Build Tools
        • Performance Settings
      • Update
        • Introduction
        • glue-reference-menu-frbdk
        • glue-reference-menu-libraries
    • Multi-Platform
      • Synced Projects
      • Changing Main Project Type
      • Android
        • Distribution
        • Setup
      • iOS
        • Certificates and Profiles
        • Copying Projects to Mac
        • Using Xamarin Build Host
      • Switch (Nintendo)
      • Web
    • Objects
      • Object Types
        • AxisAlignedRectangle
        • Camera
        • CameraControllingEntity
        • Circle
        • CollisionRelationship
        • Layer
          • DestinationRectangle
          • Is2D
        • Polygon
        • PositionedObjectList
        • RenderTarget2D
        • ShapeCollection
        • SoundEffectInstance
        • Sprite
        • Text
        • TileNodeNetwork
      • AddToManagers
      • AttachToCamera
      • AttachToContainer
      • CallActivity
      • Collidable Objects
      • EntireFile
      • ExposedInDerived
      • HasPublicProperty
      • IgnoresPausing
      • IncludeInIClickable
      • IncludeInICollidable
      • IsContainer
      • LayerOn
      • Map
      • SetByDerived
      • SourceFile
      • SourceType
    • Plugins
      • glue-gluevault-component-pages-rendertargetrenderer
      • glue-gluevault-component-pages-simple-command-console
      • glue-gluevault-component-pages-squid-gui-integration
      • kalldrexx-interactive-debugging-console
    • Profiling
    • Screens
      • AsyncLoadingState
      • BaseScreen
      • Constructor
      • Creating a New Screen
      • CustomDestroy
      • CustomInitialize
      • DefaultLayer
      • GameScreen
      • IsActivityFinished
      • IsLoadingScreen
      • LoadStaticContent
      • MoveToScreen
      • PauseAdjustedCurrentTime
      • Set as StartUp Screen
      • UnloadsContentManagerWhenDestroyed
    • States
      • InterpolateToState
      • InterpolateToState vs InterpolateBetween
      • State Categories
      • State Classes
      • States and Inheritance
      • Tunneling Category Variables
    • Variables
      • CreatesEvent
      • HasAccompanyingVelocityProperty
      • IsShared
      • Proper Variable Naming
      • SetByDerived
      • Type
      • Variable Order
    • Visual Studio Project (.csproj)
  • 🏃Animation Editor
    • Frame Time
    • Animation Shapes and Collision
  • Tiled
    • Tiled Basics
      • Introduction
      • Creating a GameScreen
      • Adding Collision
      • Colliding Entities Against TileShapeCollections
      • Working with Multiple Levels
      • Creating Entities from Tiles
      • Creating Entities from Object Layers
      • Accessing Tiled Properties
      • Working with Tiled Shapes
    • Tiled Files in Entities
    • TileEntityInstantiator
    • Using TiledObjects.Generated.xml
    • LayeredTileMap
      • Collisions
      • Destroy
      • FromTiledMapSave
      • Z
    • MapDrawableBatch
      • AddTile
      • CoordinateAdjustment
      • GetBottomLeftWorldCoordinateForOrderedTile
      • MergeOntoThis
      • NamedTileOrderedIndexes
      • PaintTile
      • PaintTileTextureCoordinates
      • ParallaxX
      • Paste
      • Properties
      • RemoveQuads
      • RenderingScale
      • SortAxis
    • TiledMapSave
    • TileShapeCollection
      • AddCollisionAtWorld
      • AddCollisionFrom
      • AddCollisionFromTilesWithProperty
      • AddMergedCollisionFromLayer
      • AddMergedCollisionFromTilesWithProperty
      • AdjustRepositionDirectionsOnAddAndRemove
      • CollideAgainst
      • CollideAgainstClosest
      • GetRectangleAtPosition
      • InsertCollidables
      • LastCollisionAxisAlignedRectangles
      • Rectangles
      • RemoveFromManagers
      • RemoveSurroundedCollision
  • 🟩Gum
    • Tutorials
      • Introduction and Setup
      • Screens in Gum
      • Gum Objects in Code
      • Events on Gum Objects
      • Events on Gum Objects Part 2
      • Exposed Variables
      • States
      • Adding Code to Gum Objects
    • Accessing Gum Screens in Code
    • Adding Components to Layers
    • Adding Gum Screens to FlatRedBall
    • Animations in Code
    • Components in FlatRedBall Entities
    • Converting Gum Coordinates
    • Creating Components in Code
    • GraphicalUiElement as IWindow
    • Gum Resolution
    • Gum Properties Tab
    • Gum Animations
      • How to Play Gum Screen Animations
      • Named Events
      • Setting Gum Animationchain Achx in Code
  • 🦴Spine
    • Setup
    • Atlas
    • Changing Spine Textures at Runtime
    • SpineDrawableBatch
      • Event
      • PlayAnimation
      • SetCollision
      • Skeleton
  • ⏸️Aseprite
    • AnimationChainList
  • 🏫API Documentation
    • FlatRedBall Engine
      • AI
        • LineOfSight
          • VisibilityGrid
        • Pathfinding
          • PositionedNode
          • Link
            • Cost
            • NodeLinkingTo
          • NodeNetwork
            • GetPath
            • UpdateShapes
            • Visible
          • TileNodeNetwork
            • AddAndLinkTiledNode
            • AddAndLinkTiledNodeWorld
            • OccupyTileWorld
            • SetCosts
      • Audio
        • AudioManager
          • AreSoundEffectsEnabled
          • CurrentlyPlayingSong
          • MasterSongVolume
          • MasterSoundVolume
          • Play
          • PlaySong
          • PlaySongs
          • StopSong
        • PositionedSound
        • Sound
      • Camera
        • AbsoluteRightXEdge
        • AbsoluteRightXEdgeAt
        • AddLayer
        • AddSpriteToBillboard
        • AspectRatio
        • AttachTo
        • BackgroundColor
        • CameraCullMode
        • ClearMinimumsAndMaximums
        • ClearsDepthBuffer
        • DestinationRectangle
        • DrawsShapes
        • DrawsToScreen
        • DrawsWorld
        • FarClipPlane
        • FieldOfView
        • FixAspectRatioYConstant
        • ForceUpdateDependencies
        • GetViewport
        • IsSpriteInView
        • KeepSpriteInScreen
        • Layer
        • Layers
        • Main
        • MaximumX
        • Orthogonal
        • OrthogonalHeight
        • OrthogonalWidth
        • PixelsPerUnitAt
        • Position
        • PositionRandomlyInView
        • RelativeXEdgeAt
        • RemoveLayer
        • RotationMatrix
        • SetBordersAtZ
        • SetLookAtRotationMatrix
        • SetSplitScreenViewport
        • UpdateViewProjectionMatrix
        • UpVector
        • UsePixelCoordinates
        • UsePixelCoordinates3D
        • View
      • Content
        • ContentLoadBatch
        • AnimationChain
          • AnimationChainListSave
        • ContentManager
          • AddUnloadMethod
          • FileAliases
          • IsAssetLoadedByName
          • Load
          • LoadFromGlobalIfExists
          • Multiple Content Managers
        • Math
          • Geometry
            • ShapeCollectionSave
        • Polygon
          • PolygonSave
        • Scene
          • CameraSave
          • SceneSave
        • SpriteEditorScene
          • Camera
      • Debugging
        • Debugger
          • CommandLineWrite
          • GetFullPerformanceInformation
          • TextBlue
          • WriteAutomaticallyUpdatedObjectInformation
      • Entities
        • CameraControllingEntity
        • IDamageable
        • IDamageArea
      • FlatRedBallServices
        • AddDisposable
        • AddManager
        • CornerGrabbingResize
        • Draw
        • ForceClientSizeUpdates
        • Game
        • GetManagerInformation
        • GlobalContentManager
        • GraphicsOptions
        • Initialize
        • IsLoaded
        • Load
        • Owner
        • Random
        • RenderAll
        • Unload
        • Update
        • WindowHandle
      • Graphics
        • Animation
          • AnimationChain
            • Clone
            • FrameToFrame
            • TotalLength
          • AnimationChainList
          • AnimationController
          • AnimationFrame
            • RelativeX
            • ShapeCollectionSave
            • Texture
          • IAnimationChainAnimatable
            • Animate
            • Animation and Timing
            • AnimationChains
            • AnimationSpeed
            • CurrentChainName
            • CurrentFrameIndex
            • JustChangedFrame
            • JustCycled
            • UseAnimationRelativePosition
        • BitmapFont
          • BMFC File
          • BitmapCharacterInfo
          • FNT File
          • Glyphs
          • LineHeightInPixels
          • RenderToTexture2D
        • BlendOperation
        • ColorOperation
          • Add
          • Color
          • ColorTextureAlpha
          • InterpolateColor
          • Modulate
          • Texture
        • GraphicsOptions
          • Filtering
          • IsFullScreen
          • ResolutionHeight
          • SetFullScreen
          • SetResolution
          • SizeOrOrientationChanged
          • TextureFilter
          • TextureLoadingColorKey
          • UseMultisampling
        • IColorable
          • Alpha
          • BlendOperation
          • Blue
          • ColorOperation
        • IDrawableBatch
          • Z
          • RenderState
        • IVisible
          • IgnoresParentVisibility
        • Layer
          • Layer Membership Details
          • LayerCameraSettings
          • Remove
          • RenderTarget
          • SortType
          • Sprites
          • UsePixelCoordinates
        • LayerCameraSettings
          • OrthogonalWidth
          • TopDestination
        • Particle
          • EmissionSettings
            • Drag
            • PixelSize
            • ScaleX
          • Emitter
        • PostProcessing
          • SwapChain
        • RenderBreak
        • Renderer
          • Draw
          • LastFrameRenderBreakList
          • RenderBreaksAllocatedThisFrame
        • Text
          • AdjustPositionForPixelPerfectDrawing
          • ColorOperation
          • DisplayText
          • GetWidth
          • Font
          • HorizontalAlignment
          • InsertNewLines
          • MaxWidth
          • MaxWidthBehavior
          • NewLineDistance
          • NumberOfLines
          • ScaleX
          • SetColor
          • SetPixelPerfectScale
          • VerticalAlignment
          • Width
        • TextManager
          • AddManuallyUpdated
          • AddText
          • AddToLayer
          • FilterTexts
          • RemoveText
        • Texture
          • RenderTargetSprite
          • ImageData
            • ApplyColorOperation
            • Fill
            • FromTexture2D
      • Gui
        • Cursor
          • Camera
          • ClickNoSlideThreshold
          • CustomUpdate
          • GetRay
          • IngnoreInputThisFrame
          • IsInWindow
          • IsOn
          • IsOn3d
          • PrimaryClick
          • PrimaryClickNoSlide
          • PrimaryPushTime
          • ScreenX
          • SecondaryClick
          • SetControllingGamepad
          • SetJoystickControl
          • TransformationMatrix
          • WindowOver
          • WidowPushed
          • WorldPosition
          • WorldX
          • WorldXAt
          • WorldYAt
          • XForUi
        • GuiManager
          • AddDominantWindow
          • BringsClickedWindowsToFront
          • BringToFront
          • GamepadsForUiControl
          • MakeRegularWindow
          • RemoveWindow
          • SortZAndLayerBased
          • Windows
        • IClickable
        • IInputReceiver
          • IWindow
            • CallClick
            • Enabled
          • ReceiveInput
      • Input
        • AnalogButton
        • AnalogStick
          • IsMaxPositionNormalized
        • DelegateBased1DInput
        • DelegateBased2DInput
        • DelegateBasedPressableInput
        • I1DInput
        • I2DInput
        • IMouseOver
        • InputDeviceBase
        • InputManager
          • ClearAllInput
          • InputReceiver
        • IPressableInput
        • Keyboard
          • Clear
          • ControlPositionedObject
          • Get2DInput
          • GetKey
          • GetStringTyped
          • IgnoreKeyForOneFrame
          • KeyDown
          • KeyPushed
        • Mouse
          • GrabbedPositionedObject
          • IsOn3D
          • ModifyMouseState
          • Restricting Mouse to Screen Bounds
          • SetScreenPosition
        • TouchScreen
          • LastFrameGestures
          • ReadsGestures
        • Windows
          • WindowsInputEventManager
        • Xbox360GamePad
          • ButtonDown
          • ButtonMap
          • ButtonPosition vs Button
          • ButtonPushed
          • ControlPositionedObject
          • CreateDefaultButtonMap
          • Deadzone
          • DeadzoneType
          • FakeIsConnected
          • GamepadLayout
          • IgnoreButtonForOneFrame
      • Instructions
        • DelegateInstruction
        • IInstructable
          • Call
          • Cnstructions
          • Set
        • Instruction
        • InstructionList
          • ExecuteAndRemoveOrCyclePassedInstructions
        • InstructionManager
          • Add
          • AddSafe
          • Instructions
          • MoveThrough
          • MoveTo
          • MoveToAccurate
          • ObjectsIgnoringPausing
          • PauseEngine
          • Pulse
          • RotateToAccurate
        • Reflection
          • LateBinder
          • PropertyCollection
        • MethodInstruction
        • StaticMethodInstruction
      • IO
        • Csv
          • CsvHeader
          • CsvFilemanager
            • Cells with Multiple Lines
            • Color
            • CsvDeserializelist
            • Rows with Lists
          • RuntimeCsvRepresentation
            • FromList
            • GenerateCsvString
        • FileManager
          • BinarySerialize
          • CloneObject
          • FromFileText
          • GetAllFilesInDirectory
          • GetUserFolder
          • InitializeUserFolder
          • RelativeDirectory
          • SaveEmbeddedResource
          • SaveText
          • Standardize
          • UserApplicationDataForThisApplication
          • XmlDeserialize
          • XmlSerialize
      • Localization
        • LocalizationManager
      • Managers
        • IManager
      • Math
        • IAttachableRemovable
        • AttachableList
          • FindByName
          • MakeOneWay
        • Collision
          • CollisionManager
            • Relationships
            • Update
        • Geometry
          • AxisAlignedCube
            • CollideAgainstBounce
          • AxisAlignedRectangle
            • Axis Alignment And Rotation
            • CollideAgainstMoveSoft
            • Color
            • GetRandomPositionInThis
            • KeepThisInsideOf
            • LastMoveCollisionReposition
            • Left
            • RepositionDirections
          • Capsule2D
          • Circle
            • CollideAgainst
            • CollideAgainstBounce
            • CollideAgainstMove
            • IsPointInside
            • LastCollisionTangent
            • LastMoveCollisionReposition
            • ProjectParentVelocityOnLastMoveCollisionTangent
            • Visible
            • Z
          • Colliding a List of Shapes Against Itself
          • FloatRectangle
          • ICollidable
          • IScalable
            • Scale
          • Line
            • Color
            • LastCollisionPoint
            • RelativePoint1
            • SetFromAbsoluteEndpoints
          • Point
          • Polygon
            • AbsolutePointPosition
            • Clone
            • CollideAgainstBounce
            • CollideAgainstMove and Attachments
            • CollideAgainstMove
            • Color
            • CreateEquilateral
            • CreateRectangle
            • ForceUpdateDependencies
            • IsPointInside
            • LastMoveCollisionReposition
            • OptimizeRadius
            • Points
            • Position
            • ProjectParentVelocityOnLastMoveCollisionTangent
            • ScaleBy
            • Thin Polygon Problem
            • VectorFrom
            • Visible
            • Z
          • Segment
            • ClosestPointTo
          • Shape
          • ShapeCollection
            • AttachTo
            • AxisAlignedRectangles
            • CollideAgainst
            • CollideAgainstBounceWithoutSnag
            • CollideAgainstMove
            • CollideAgainstMoveWithoutSnag
            • LastCollisionAxisAlignedRectangles
            • SortAscending
            • Visible
          • ShapeManager
            • AddToLayer
            • Remove
            • ShapeDrawingOrder
          • ShapeMerger
          • Shapes and 2D Collision
          • Sphere
        • IAttachable
          • Attachment Updates in the Engine
          • Detach
          • ParentRotationChangesPosition
          • ParentRotationChangesRotation
          • TopParent
        • IRotatable
          • RotationMatrix
        • MathFunctions
          • AbsoluteToWindow
          • AngleToAngle
          • AngleToVector
          • GetPointInCircle
          • GetPositionAfterTime
          • RegulatAngle
          • RotatePointAroundPoint
          • RoundFloat
          • RoundToInt
          • WidowToAbsolute
        • Paths
          • Path
        • PositionedObjectList
          • Add
          • AttachTo
          • Clear
          • GetFirstAfter
          • GetFirstAfterPosition
          • SortXInsertionAscending
        • Splines
          • Spline
            • GetPositionAtLengthAlongSpline
      • Performance
        • Measurement
          • Section
            • GetAndStartContextAndTime
            • Save
            • ToStringVerbose
      • PositionedObject
        • Acceleration
        • AttachTo
        • Children
        • Clone
        • Drag
        • ForceUpdatedependencies
        • ForceUpdatedependenciesDeep
        • Initialize
        • KeepTrackOfReal
        • LastPosition
        • Mirrored properties
        • ParentRotationChangesPosition
        • ParentRotationChangesRotation
        • Position
        • RelativePosition
        • RelativeRotationZ
        • RelativeVelocity
        • RemoveSelfFromListsBelongingTo
        • RotationZ
        • SetRelativeFromAbsolute
        • TimedActivity
        • TopParent
        • UpdateDependencies
        • Velocity
        • Z
      • Screens
        • Screen
          • ContentManagerName
          • CustomDestroy
          • IsActivityFinished
          • MoveToScreen
          • PauseThisScreen
        • ScreenManager
          • Activity
          • CurrentScreen
          • Start
      • Sprite
        • Alpha
        • AnimateSelf
        • AnimationChains
        • AnimationSpeed
        • Bottom
        • BottomTextureCoordinate
        • Changing a Sprite's Origin
        • ColorOperation
        • CurrentChainName
        • CurrentFrameIndex
        • IgnoreAnimationChainTextureFlip
        • Inheriting from the Sprite Class
        • JustCycled
        • LeftTextureCoordinate
        • PixelSize
        • Position
        • RightTextureCoordinate
        • SetAnimationChain
        • SetScaleXRatioToY
        • Sorting and Overlapping
        • Sprite vs Texture2d
        • Texture Coordinates
        • Texture
        • TextureAddressMode
        • TextureCoordinate
        • TextureFilter
        • TextureScale
        • TimeIntoAnimation
        • TopTextureCoordinate
        • UseAnimationRelativePosition
        • Vertices
        • VerticesForDrawing
        • Visible
      • SpriteList
      • SpriteManager
        • AddDrawableBatch
        • AddManagedInvisibleSprite
        • AddManualSprite
        • AddParticleSprite
        • AddPositionedObject
        • AddSprite
        • AddToLayer
        • AddZBufferedDrawableBatch
        • AddZBufferedSprite
        • AutomaticallyUpdatedSprites
        • Camera
        • ConvertToAutomaticallyUpdated
        • ConvertToManagedInvisible
        • ConvertToManuallyUpdated
        • ConvertToZBufferedSprite
        • DrawableBatches
        • ManagedPositionedObjects
        • ManualUpdate
        • MaxParticleCount
        • MoveToBack
        • OrderedSortType
          • Z
        • OrderedSprites
        • RemoveDrawableBatch
        • RemoveLayer
        • RemovePositionedObject
        • RemoveSprite
        • RemoveSpriteOneWay
        • SortTexturesSecondary
        • SortYSpritesSecondary
        • UnderAllDrawnLayer
      • TimeManager
        • Accumulating Time
        • CurrentScreenSecondsSince
        • CurrentTime
        • Profiling
        • SecondDifference
        • SecondsSince
        • SumTimeSection
        • SystemCurrentTime
        • TimeFactor
        • Working with TimeSpan
      • Utilities
        • StringFunctions
    • FlatRedBall.Forms
      • Controls
        • Button
        • CheckBox
        • ComboBox
        • FrameworkElement
          • DefaultFormsComponents
          • HandleTab
          • Show
          • Visual
        • Games
          • DialogBox
          • OnScreenKeyboard
          • SettingsView
        • ListBox
        • ListBoxItem
        • RadioButton
        • ScrollBar
        • ScrollViewer
        • Slider
        • StackPanel
        • TextBox
        • TreeView
        • TreeViewItem
      • MVVM
        • DependsOnAttribute
    • FlatRedBall Editor Plugin
      • customvariable
      • Introduction
      • flatredball-glue-elements-objectfinder
      • flatredball-glue-guidisplay-propertygriddisplayer
      • Introduction
      • flatredball-glue-projectmanager
      • Introduction
      • flatredball-glue-saveclasses-namedobjectsave
      • flatredball-glue-saveclasses-referencedfilesave
      • flatredball-glue
        • plugins
          • flatredball-glue-exportedinterfaces-igluestate
          • flatredball-glue-exportedinterfaces-igluxcommands-addreferencedfiletoglobalcontent
          • flatredball-glue-exportedinterfaces-igluxcommands
          • Introduction
          • flatredball-glue-exportedinterfaces-iprojectcommands-makeabsolute
          • flatredball-glue-exportedinterfaces-iprojectcommands
          • flatredball-glue-interfaces-icodegeneratorplugin
          • flatredball-glue-interfaces-imenustripplugin
          • Introduction
          • flatredball-glue-pluginbase-getfilesreferencedby
          • flatredball-glue-pluginbase
          • Introduction
        • vshelpers
          • codebuilditemadder
    • FlatRedBall Editor (Glue)
      • AssetTypeInfo
      • Cleaning Up Screens
      • CodeGeneration
        • ICodeBlock
      • CustomActivity
      • CustomLoadStaticContent
      • Entity
        • Introduction
        • glue-reference-entities-destroy
      • Game1CodeGenerator
      • GetFile
      • PauseThisScreen
      • SaveClasses
        • GlueSettingsSave
      • Screen
        • glue-reference-screens-pauseadjustedsecondssince
    • Live Edit
      • EditorVisuals
        • Circle
        • Text
      • Instance Creation
    • Gum Runtime
      • GraphicalUiElement
        • GetAbsoluteLeft
        • GetGraphicalUiElementByName
        • HasCursorover
        • InterpolateBetween
        • InterpolateTo
        • MoveToFrbLayer
        • RaiseChildrenEventsOutsideOfBounds
        • SetProperty
        • ShowLineRectangles
        • TestCollision
      • RenderingLibrary
        • camera
        • ipositionedsizedobject
        • graphics
          • Layer
          • text
            • textrenderingmode
    • iOS
      • uikit-uiviewcontroller
    • Microsoft.Xna.Framework
      • Audio
        • SoundEffect
        • SoundEffectInstance
      • Color
      • Introduction
      • Game
        • IsActive
        • IsFixedTimeStep
        • IsMouseVisible
        • TargetElapsedTime
      • GameWindow
        • Introduction
        • Introduction
        • handle
      • Graphics
        • Shared Parameters
        • model
        • spritebatch
        • GraphicsDevice
          • renderstate
          • SetRenderTarget
        • renderstate
          • referencealpha
        • Texture2D
          • Creating New Textures Programatically
      • GraphicsDeviceManager
        • supportedorientations
      • Media
        • MediaPlayer
        • Song
          • FromUri
      • Vector3
    • NAudio
      • NAudio_Song
    • SkiaGum
      • SkiaSpriteCanvas
      • Renderables
        • RenderableSkiaObject
    • State Interpolation
      • Tween
      • Tweener
      • TweenerManager
  • 🏘️Contributing
    • How to Contribute
    • Builds (Releases)
      • Gum
    • Writing Documentation
    • Contributing Code (Pull Requests)
    • Automated Test Project
    • Programming Style Guide
  • 🎮FlatRedBall Games
    • angry-boy
    • avatar-skate
    • avatar-word-wave
    • bobble-biker
    • box-the-gopher
    • cargo-crush
    • combo-red-moon-rising
    • cubism
    • eat-my-shuriken-and-die
    • elemento
    • food-battler
    • free-towels
    • gravi-dot
    • hyperdodge
    • juice-factory
    • operation-sd-space-defense
    • picture-puzzle-revolution
    • prismatic
    • quarantine
    • quest-for-freshness
    • star-stepper
    • steambirds
    • sticky-bump
    • tile-trip
    • trashman
    • tumble-heads
    • udder-chaos
    • without-escape
    • games-oniro
  • 🔴FlatRedBall Logo
  • Installing XNA in Visual Studio 2017
Powered by GitBook
On this page
  • Introduction
  • Collision Relationships
  • Creating a Collidable Entity
  • Example - Entity vs. Entity Collision
  • Example - Entity List Relationships
  • Example - Entity/Entity List vs. TileShapeCollection
  • Example - Move Collision
  • Example - Bounce Collision with Per-Entity Mass
  • Example - Partitioning
  • Counting Collisions
  • Example - SubCollision
  • Example: Optional Collision Physics
  • Manual Collision with DoCollisions

Was this helpful?

Edit on GitHub
Export as PDF
  1. API Documentation
  2. FlatRedBall Engine
  3. Math
  4. Collision

CollisionManager

PreviousCollisionNextRelationships

Last updated 11 months ago

Was this helpful?

Introduction

The CollisionManager class provides methods for handling collision (the touching of game objects) in FlatRedBall games. The CollisionManager has built-in methods for handling collision between collidable entities (entities which implement the ICollidable interface). Use of the CollisionManager is not necessary, but it can reduce and standardize code for handling collisions. The CollisionManager provides a rich set of functionality for performing collision in code, but usually games do not need to write code against the CollisionManager. Instead, the FlatRedBall Editor provides support for creating CollisionRelationships without any code. For more information, see the .

Collision Relationships

The CollisionManager is built around the concept of collision relationships. A collision relationship is created by specifying the two objects (or groups of objects) which are used in the relationship. The following list shows common relationships in games:

  • Player vs. Enemy Bullet List

  • Player Bullet List vs. Environment

  • Race Car List vs. Boost Entity List

  • Explosion List vs. Destructible Block List

The relationship detects collision and provides automatic and custom handling of the collision. Automatic handling includes separating objects (preventing overlapping) and adjusting the velocity of colliding objects (bouncing the objects). Custom handling is done by assigning a collision event.

Creating a Collidable Entity

The CollisionManager is built to work with collidable entities. To create a collidable entity in Glue:

  1. Open Glue

  2. Right-click on the Entities folder

  3. Click Add Entity

  4. Check one of the objects under the Collisions category, such as Circle

  5. Notice that the ICollidable checkbox is automatically checked

The entity will now implement the ICollidable interface, which means it can be used as an instance or in a list with the CollisionManager.

Example - Entity vs. Entity Collision

A relationship may define that two individual entities should perform collision logic against one another. The following assumes that PlayerInstance and EnemyInstance are entities added to the screen in Glue:

private void CreateCollisionRelationships()
{
    var relationship = CollisionManager.Self.CreateRelationship(
        PlayerInstance, EnemyInstance);
    relationship.CollisionOccurred = HandlePlayerVsEnemyCollision;
}

private void HandlePlayerVsEnemyCollision(Player player, Enemy enemy)
{
    enemy.TakeDamage();
    player.TakeDamage();
}

Notice that the HandlePlayerVsEnemyCollision is used to perform custom logic whenever a collision occurs.

Example - Entity List Relationships

Entities which are dynamically created or destroyed during the life of a screen (such as bullets fired by a turret) are usually added to lists. The following code can be used to detect collision between a single Player instance and a list of Bullets:

private void CreateCollisionRelationships()
{
    var relationship = CollisionManager.Self.CreateRelationship(
        PlayerInstance, BulletList);
    relationship.CollisionOccurred = HandlePlayerVsBulletCollision;
}

private void HandlePlayerVsBulletCollision(Player player, Bullet bullet)
{
    bullet.Destroy();
    player.TakeDamage();
}

Notice that the CollisionOccurred delegate passes a single bullet even though the type passed to CreateRelationship is a list. This allows the code to handle collision on a case-by-case basis. Similarly, relationships can be created between two lists. The following example shows how to respond to collision between a list of Enemies and a list of Bullets:

private void CreateCollisionRelationships()
{
    var relationship = CollisionManager.Self.CreateRelationship(
        EnemyList, BulletList);
    relationship.CollisionOccurred = HandleEnemyVsBulletCollision;
}

private void HandleEnemyVsBulletCollision(Enemy enemy, Bullet bullet)
{
    bullet.Destroy();
    player.TakeDamage();
}

Example - Entity/Entity List vs. TileShapeCollection

Entities can be collied against TileShapeCollections through the CollisionManager. TileShapeCollections are an efficient and convenient way to store a group of rectangles for collision.

// Since this is an extension method, you must have the following
// using statement in your class:
using FlatRedBall.Math.Collision;

private void CreateCollisionRelationships()
{
    // SolidCollisions is assumed to be a TileShapeCollection
    var relationship = CollisionManager.Self.CreateTileRelationship(PlayerList, SolidCollisions);
    // Make it so the solid collisions can't be moved:
    relationship.SetMoveCollision(0, 1);
}

See the Move Collision section below for more information.

Example - Move Collision

Collision relationships can specify automatic behavior in addition to assigning the CollisionOccurred delegate. This can be achieved by calling various Set methods. For example, the following results in colliding objects being separated. The SetMoveCollision method takes the relative masses of each object. In this example the colliding player and blocks have equal mass:

private void CreateCollisionRelationships()
{
    var relationship = CollisionManager.Self.CreateRelationship(
        Player, BlockList);
    var playerMass = 1;
    var blockMass = 1;
    relationship.SetMoveCollision(playerMass, blockMass);
    // custom collision can also be handled if needed
}

The most common ways to call is either with the values of (0,1) and (1,1)

  • (0,1) - The first object (typically an entity) will have a mass of 0, meaning it will not be able to move the second object.

  • (1,1) - Both objects have equal masses, and will push each other

Example - Bounce Collision with Per-Entity Mass

Both Move and Bounce collisions can be performed automatically by the relationship by calling either SetMoveCollision or SetBounceCollision. While convenient, these methods require the same mass to be used for all entities in a relationship. In some cases entities may need to have a custom mass per entity. In this example a list of asteroids collides with itself (every asteroid tests for collision against every other asteroid). Each Asteroid has a different Mass value so we can't set one mass for the entire relationship. Instead, the collision is detected and an event is raised, then the bounce collision occurs inside the collision event handler.

private void CreateCollisionRelationships()
{
    var relationship = CollisionManager.Self.CreateRelationship(
        AsteroidList, AsteroidList);
    relationship.CollisionOccurred = HandleAsteroidVsAsteroidCollision;
}

private void HandleEnemyVsBulletCollision(Asteroid first, Asteroid second)
{
    const float elasticity = .5f;
    first.CollideAgainstBounce(second, first.Mass, second.Mass, elasticity);
}

Note that the example above shows how to do self-collision, but the same approach of handling the move or bounce collision in an event could be performed between two different separate lists.

Example - Partitioning

The CollisionManager can perform partitioning to improve collision performance. In most cases partitioning can make even large numbers of objects (tens of thousands) have minimal or no impact on your game's frame rate. Partitioning requires two pieces of information:

  1. The axis to partition (X or Y). This should be the axis along which objects are most distributed. For example, a platformer with horizontal levels should partition on the X axis.

  2. The width or height of each object involved in partitioning.

Both objects in a relationship must be partitioned on the same axis before a relationship will be able to use the partitioning to reduce collision calls. Partitioned objects must be sorted for partitioning to function properly. If the order of objects in the list can change, the CollisionManager can automatically sort the lists. If the order does not change once the list has been created, or if the order is explicitly maintained in custom code, then the sortEveryFrame parameter can be false. The following creates a partitioned collision relationship between a list of Enemies and a list of Bullets.

private void CreateCollisionRelationships()
{
    var maxEnemyWidth = 48;
    var maxBulletWidth = 12;
    CollisionManager.Self.Partition(EnemyList, FlatRedBall.Math.Axis.X, 
        maxEnemyWidth, sortEveryFrame = true);
    CollisionManager.Self.Partition(BulletList, FlatRedBall.Math.Axis.X, 
        maxBulletWidth, sortEveryFrame = true);

    var relationship = CollisionManager.Self.CreateRelationship(EnemyList, BulletList);
    relationship.CollisionOccurred += HandeEnemyVsBulletCollision;
}

private void HandeEnemyVsBulletCollision(Enemy enemy player, Bullet bullet)
{
    ...
}

Partitioning must set on both objects in a relationship even if one of the objects is a single instance - in that case the Partition call is needed to get the width or height of the object's collision.

private void CreateCollisionRelationships()
{
    var maxPlayerWidth = 30;
    var maxBulletWidth = 12;
    CollisionManager.Self.Partition(Player, FlatRedBall.Math.Axis.X, 
        maxPlayerWidth);
    CollisionManager.Self.Partition(BulletList, FlatRedBall.Math.Axis.X, 
        maxBulletWidth, sortEveryFrame = true);

    var relationship = CollisionManager.Self.CreateRelationship(Player, BulletList);
    relationship.CollisionOccurred += HandeEnemyVsBulletCollision;
}

private void HandeEnemyVsBulletCollision(Enemy enemy player, Bullet bullet)
{
    ...
}

The Partition method only needs to be called once, even if an object is used in multiple relationships.

private void CreateCollisionRelationships()
{
    var maxPlayerWidth = 30;
    var maxBulletWidth = 12;
    var maxEnemyWidth = 28;

    // Partition is only called one time on Player, even though
    // Player is used in multiple relationships.
    CollisionManager.Self.Partition(Player, FlatRedBall.Math.Axis.X, 
        maxPlayerWidth);
    CollisionManager.Self.Partition(BulletList, FlatRedBall.Math.Axis.X, 
        maxBulletWidth, sortEveryFrame = true);
    CollisionManager.Self.Partition(EnemyList, FlatRedBall.Math.Axis.X, 
        maxEnemyWidth, sortEveryFrame = true);


    var playerVsBulletRelationship = CollisionManager.Self.CreateRelationship(
        Player, BulletList);
    playerVsBulletRelationship.CollisionOccurred += HandlePlayerVsBulletCollision;

    var playerVsEnemyRelationship = CollisionManager.Self.CreateRelationship(
        Player, EnemyList);
    playerVsEnemyRelationship.CollisionOccurred += HandlePlayerVsEnemyCollision;
}

Counting Collisions

In general reducing collision count improves the performance of your game. To measure whether your efforts to reduce collision are working (such as by implementing partitioning), the CollisionManager returns the number of deep collisions performed every frame. The term deep collision refers to collision methods which rely on the actual shapes of a collidable object, as opposed to partitioned checks which can eliminate large numbers of objects very quickly. The following code shows how to count and display the number of collisions performed every frame:

void CustomActivity(bool firstTimeCalled)
{
    FlatRedBall.Debugging.Debugger.Write(
        CollisionManager.Self.DeepCollisionsThisFrame);
}

Example - SubCollision

Entities may include multiple collision objects used for different responses. For example, a SpaceShip entity may have a small collision shape for its body (for taking damage) and a larger collision shape for a radar ( to detect enemies and display them on a radar HUD). Collision relationships will use the entire entity by default, but can be configured to only use a single shape by calling SetFirstSubCollision or SetSecondSubCollision for the first or second object in the relationship, respectively. The following code shows how to handle SpaceShip body vs. a list of Bullets:

private void CreateCollisionRelationships()
{
    var relationship = CollisionManager.Self.CreateRelationship(SpaceShipInstance, BulletList);
    relationship.CollisionOccurred += HandleSpaceShipVsBulletCollision;
    relationship.SetFirstSubCollision(spaceShip => spaceShip.CircleInstance);
}

SetFirstSubCollision refers to the first argument in the CreateRelationship call, which is SpaceShipInstance in the example above. SetSecondSubCollision refers to the second argument in the CreateRelationship call, which is BulletList in the example above. Note that if the argument to CreateRelationship is a list, then the SetFirstSubCollision and SetSecondSubCollision will work with a single instance rather than a list. For example, the code above could call SetSecondSubCollision for the BulletList , but the argument would take a single bullet as shown in the following snippet:

private void CreateCollisionRelationships()
{
    var relationship = CollisionManager.Self.CreateRelationship(SpaceShipInstance, BulletList);
    ...
    // Note we use "bullet" and not the entire list in this call:
    relationship.SetSecondSubCollision(bullet => bullet.CircleInstance);
}

SubCollision and Partitioning

When using a sub collision, the partition values may be different to account for the different collision object size. For example, the body of a space ship may be much smaller than the radar. Relationships can override the width or height values used for partitioning. The following code shows how to provide different collision width values (for X axis partitioning) for radar and body collision relationships:

private void CreateCollisionRelationships()
{
    // The Partition calls will define the default width values for the ship, bullet, and enemy entities,
    // which can be overridden by calling SetPartitioningSize on relationships.
    var defaultShipWidth = 48;
    var maxBulletWidth = 12;
    var maxEnemyWidth = 54;
    CollisionManager.Self.Partition(SpaceShipInstance, FlatRedBall.Math.Axis.X, defaultShipWidth);
    CollisionManager.Self.Partition(BulletList, FlatRedBall.Math.Axis.X, maxBulletWidth);
    CollisionManager.Self.Partition(EnemyList, FlatRedBall.Math.Axis.X, maxEnemyWidth);
    
    var shipVsBulletRelationship = CollisionManager.Self.CreateRelationship(
        SpaceShipInstance, BulletList);
    shipVsBulletRelationship.SetFirstSubCollision(spaceShip => spaceShip.BodyCollision);
    // Only the enemy's partition size is overridden for this relationship. Bullets will use default width
    var spaceShipBodyCollisionWidth = 25;
    shipVsBulletRelationship.SetPartitioningSize(SpaceShipInstance, spaceShipBodyCollisionWidth);

    var spaceShipRadarVsEnemyRelationship = CollisionManager.Self.CreateRelationship(
        SpaceShipInstance, EnemyList);
    spaceShipRadarVsEnemyRelationship.SetFirstSubCollision(spaceShip => spaceShip.RadarCollision);
    // As with the relationship above, we only override the ship width for this collision. 
    // Enemies will use the default width.
    var spaceShipRadarCollisionWidth = 200;
    spaceShipRadarVsEnemyRelationship.SetPartitioningSize(SpaceShipInstance, spaceShipRadarCollisionWidth);


}

Example: Optional Collision Physics

At times collision physics needs to be applied optionally. For example, a Player may be able to transform into a ghost. Normally the player may perform solid collision (Move or Bounce) against enemies, but while in the ghost phase the player can move through enemies. This can be done by telling the collision relationship to optionally apply collision as shown in the following code:

// Assuming PlayerVsEnemy is a valid collision relationship
PlayerVsEnemy.ArePhysicsAppliedAutomatically = false;
PlayerVsEnemy.CollisionOccurred += PlayerVsEnemyCollided;
// handle the event:
void PlayerVsEnemyCollided (Entities.Player player, Entities.Enemy enemy)
{
    if(player.IsGhost == false)
    {
        PlayerVsEnemy.DoCollisionPhysics(player, enemy);
    }
}

Manual Collision with DoCollisions

The default behavior for relationships is to perform collisions every-frame. The CollisionRelationship class provides additional control for when collisions are called. The DoCollisions method can be called in custom code to perform collisions as desired. This can be useful if collisions need to happen after certain logic has executed in a frame, or only in certain situations. The following code shows how to create a CollisionRelationship which is only collided when the user holds the Space key:

CollisionRelationship relationship;

private void CreateCollisionRelationships()
{
    relationship = CollisionManager.Self.CreateRelationship(
        PlayerInstance, BulletList);

    // Tell the CollisionManager to not automatically run collision every-frame
    relationship.IsActive = false;
}

void CustomActivity()
{
    if(InputManager.Keyboard.KeyDown(Keys.Space))
    {
        relationship.DoCollisions();
    }
}
🏫
FlatRedBall Editor CollisionRelationship page