### Initialize Game Start Screen (C#) Source: https://docs.flatredball.com/flatredball/api/flatredball/screens/screenmanager/start This C# code snippet demonstrates how to call the FlatRedBall ScreenManager's Start method to set the initial game screen. It requires the type of the screen to be passed as an argument. This is typically found in the Game1.cs file. ```csharp FlatRedBall.Screens.ScreenManager.Start(typeof(GameName.Screens.GameScreen)); ``` -------------------------------- ### Asset and Collection Type Examples in FlatRedBall API Source: https://docs.flatredball.com/flatredball/api/flatredball/io/csv/csvfilemanager Details C# member variable declarations and CSV entry examples for asset types like Texture2D and collection types like List. ```csharp public Texture2D TextureToUse; // CSV Entry Example: redball.bmp // Note: Requires a content manager. ``` ```csharp public List Names = new List(); // CSV Entry Example: See external article for details. ``` -------------------------------- ### String and Enum Type Examples in FlatRedBall API Source: https://docs.flatredball.com/flatredball/api/flatredball/io/csv/csvfilemanager Shows C# member variable declarations and CSV entry examples for string and enum types, including notes on enum qualification. ```csharp public string FirstName; // CSV Entry Example: Martin ``` ```csharp public BorderSides Sides; // CSV Entry Example: Top // Note: For enums in Glue, fully-qualify the type in the header, e.g., ColorOp (FlatRedBall.Graphics.ColorOperation) ``` -------------------------------- ### Apply Velocity and Acceleration to Polygons Source: https://docs.flatredball.com/flatredball/api/flatredball/positionedobject Shows how to set the velocity and acceleration for Polygon objects, which are then automatically applied by the ShapeManager. This example illustrates movement and simulated gravity. ```csharp // Add the following using to qualify Polygon and ShapeManager: // using FlatRedBall.Math.Geometry Polygon polygon = Polygon.CreateRectangle(3, 3); ShapeManager.AddPolygon(polygon); // so it is automatically managed polygon.XVelocity = -3; Polygon secondPolygon = Polygon.CreateRectangle(5, 2); ShapeManager.AddPolygon(secondPolygon); secondPolygon.Velocity = new Vector3(3, 5, 0); secondPolygon.Acceleration.Y = -3; ``` -------------------------------- ### Get Ray from Cursor Position and Camera Direction (C#) Source: https://docs.flatredball.com/flatredball/api/flatredball/gui/cursor/getray This C# code snippet demonstrates how to use the GuiManager.Cursor.GetRay() method to obtain a Ray object. This Ray represents the cursor's current position and the direction of the camera, allowing for advanced object picking. It includes setup for a reference circle and makes the mouse cursor visible. The example also shows how to control the camera's position using keyboard input. ```csharp void CustomInitialize() { // Add a circle for reference: Circle circle = ShapeManager.AddCircle(); circle.Radius = 64; // so we can see the cursor: FlatRedBallServices.Game.IsMouseVisible = true; } void CustomActivity(bool firstTimeCalled) { var ray = GuiManager.Cursor.GetRay(); FlatRedBall.Debugging.Debugger.Write( "Ray Position: " + ray.Position + "\n" + "Ray Direction: " + ray.Direction); // let's move the camera around too to make sure this works: const float velocity = 50; InputManager.Keyboard.ControlPositionedObject(Camera.Main, velocity); } ``` -------------------------------- ### Initialize Text Object and Mouse Visibility Source: https://docs.flatredball.com/flatredball/api/flatredball/input/mouse/ison3d Sets up mouse visibility and creates a Text object for display. The text's position is adjusted to avoid rendering issues. ```csharp IsMouseVisible = true; text = TextManager.AddText("Hi, I am some text."); text.X = .1f; // do this so the text doesn't appear between pixels text.Y = .1f; ``` -------------------------------- ### Unmanaged PositionedObject Initialization (C#) Source: https://docs.flatredball.com/flatredball/api/flatredball/positionedobject Illustrates the initialization of a PositionedObject without adding it to a manager. This results in properties like XVelocity not being applied automatically, meaning the object will not move across the screen without explicit management. ```csharp PositionedObject myObject = new PositionedObject(); myObject.XVelocity = 1; // this won't be applied until added to the SpriteManager ``` -------------------------------- ### Get 2D Input from Xbox360 Gamepad Analog Stick (C#) Source: https://docs.flatredball.com/flatredball/api/flatredball/input/i2dinput Shows a C# example of accessing the left analog stick of the first Xbox360 gamepad to get an I2DInput object. This is commonly used for analog movement control. ```csharp var input = InputManager.Xbox360GamePads[0].LeftStick; ``` -------------------------------- ### Configure Sub-Collision for SpaceShip vs. Single Bullet (C#) Source: https://docs.flatredball.com/flatredball/api/flatredball/math/collision/collisionmanager This example refines the sub-collision setup by specifying which part of the second entity (a single bullet from the BulletList) should be used for collision detection with the SpaceShip. It highlights how to target individual elements within a list for collision. ```csharp 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); } ``` -------------------------------- ### Create and Sort Sprites by Distance from Camera (C#) Source: https://docs.flatredball.com/flatredball/api/flatredball/spritemanager/orderedsorttype This example creates 10 sprites, scales and rotates them, and then sets the OrderedSortType to DistanceFromCamera. This ensures proper overlapping regardless of camera position, making it ideal for dynamic camera movements. ```csharp for (int i = 0; i < 10; i++) { Sprite sprite = SpriteManager.AddSprite("redball.bmp"); sprite.Y = - 15 + 3 * i; sprite.ScaleX = sprite.ScaleY = 12f; sprite.RotationX = 1.57f; } SpriteManager.OrderedSortType = SortType.DistanceFromCamera; ``` -------------------------------- ### Get IPressableInput from Common Input Devices (C#) Source: https://docs.flatredball.com/flatredball/api/flatredball/input/ipressableinput This section provides C# examples for obtaining IPressableInput objects from various common input devices in FlatRedBall, including keyboard keys, mouse buttons, and Xbox 360 gamepad buttons and D-pad directions. ```csharp // Keyboard IPressableInput input = InputManager.Keyboard.GetKey(Keys.Space); ``` ```csharp // Mouse IPressableInput input = InputManager.Mouse.GetButton(Mouse.MouseButtons.LeftButton); ``` ```csharp // Xbox360GamePad Button IPressableInput input = InputManager.Xbox360GamePads[0].GetButton(Xbox360GamePad.Button.A); ``` ```csharp // Xbox360GamePad DPad IPressableInput input = InputManager.Xbox360GamePads[0].GetButton(Xbox360GamePad.Button.DPadLeft); ``` ```csharp // Xbox360GamePad Analog Stick (Pressing to the right on the left thumb stick) IPressableInput input = InputManager.Xbox360GamePads[0].LeftStick.RightAsButton; ``` -------------------------------- ### Instantiate Entity in Custom Code (C#) Source: https://docs.flatredball.com/flatredball/api/glue-runtime-api/glue-reference-code-customloadstaticcontent Demonstrates instantiating an Entity in custom C# code. Glue does not automatically load static content for entities created this way, potentially causing performance issues. Manual loading via `CustomLoadStaticContent` is recommended. ```csharp Player mPlayer; private void CustomInitialize() { mPlayer = new Player(ContentManagerName); } ``` -------------------------------- ### Reset Current Screen (C#) Source: https://docs.flatredball.com/flatredball/api/flatredball/screens/screen/movetoscreen This snippet illustrates how to reset the current screen to its initial state by calling MoveToScreen with the screen's own type. This action effectively destroys and then recreates the current screen, providing a way to revert to the starting configuration, for example, after a player loses a life. ```csharp // assuming there is a function to tell us if the player was hit by a bullet // This also assumes that this code is written in the GameScreen and not in an entity bool wasHitByBullet = GetIfHitByBullet(); if(wasHitByBullet) { // GetType returns the GameScreen's type this.MoveToScreen(this.GetType()); } ``` -------------------------------- ### Create and Execute a FlatRedBall Instruction Source: https://docs.flatredball.com/flatredball/api/flatredball/instructions/instruction Demonstrates how to create a new Instruction for a PositionedObject, setting its 'X' property to a value at a future time. It also shows how to manually execute the Instruction multiple times. ```csharp Instruction instruction = new Instruction( objectInstance, "X", 5, TimeManager.CurrentTime + 10)); instruction.Execute(); // it's still valid, we can do it again instruction.Execute(); // we can do this over and over - the Instruction does not destroy or invalidate itself instruction.Execute(); ``` -------------------------------- ### Save Text to Application Data Folder (C#) Source: https://docs.flatredball.com/flatredball/api/flatredball/io/filemanager/userapplicationdataforthisapplication This example demonstrates how to save a string to a file named 'myFile.txt' within the application's data directory. It utilizes the FileManager.UserApplicationDataForThisApplication property to get the correct path and FileManager.SaveText to write the content. Ensure the FileManager class and its methods are accessible. ```csharp string stringToSave = "Hello World"; string locationToSave = FileManager.UserApplicationDataForThisApplication + "myFile.txt"; FileManager.SaveText(stringToSave, locationToSave); ``` -------------------------------- ### Optional Content Loading Based on Level (C#) Source: https://docs.flatredball.com/flatredball/api/glue-runtime-api/glue-reference-code-customloadstaticcontent Provides an example of conditionally loading static content for different Entity types based on global game state, such as the current level type. This allows for optimized loading, only loading assets that are actually needed for the current game segment. ```csharp if(GlobalData.CurrentLevel.LevelType == LevelType.OrcLevel) { Orc.LoadStaticContent(contentManagerName); } else if(GlobalData.CurrentLevel.LevelType == LevelType.TrollLevel) { Troll.LoadStaticContent(contentManagerName); } ``` -------------------------------- ### Create Button Instance Programmatically in C# Source: https://docs.flatredball.com/flatredball/api/flatredball-forms/controls/button Shows how to create a Button instance entirely through code, including setting its visual representation, adding it to the display, setting its text, and attaching event handlers for 'Click' and 'Push' events. This allows for dynamic button creation. ```csharp void CustomInitialize() { // This will construct a button using the default // visual which should be set-up by Glue, or which can be // manually set up in code. var button = new Button(); button.Visual.AddToManagers(); button.Text = "Hello"; button.Click += HandleButtonClick; button.Push += HandleButtonPush; } private void HandleButtonClick(object sender, EventArgs e) { // handle click logic here } private void HandleButtonPush(object sender, EventArgs e) { // handle push logic here } ``` -------------------------------- ### Custom and Color Type Examples in FlatRedBall API Source: https://docs.flatredball.com/flatredball/api/flatredball/io/csv/csvfilemanager Provides C# member variable declarations and CSV entry examples for custom types (classes/structs) and the Color type. ```csharp public SpecialAbility AbilityInstance; // CSV Entry Example: See external article for details. ``` ```csharp public Color PaintColor; // CSV Entry Example: See external article for details. ``` -------------------------------- ### Loading Same Asset with Different Content Managers (C#) Source: https://docs.flatredball.com/flatredball/api/flatredball/content/contentmanager Demonstrates loading the same asset ('redball.bmp') multiple times, each with a different content manager name. This results in separate copies of the texture in memory, as content manager names are case-sensitive. ```csharp SpriteManager.AddSprite("redball.bmp", "Some Content Manager"); SpriteManager.AddSprite("redball.bmp", "Other Content Manager"); SpriteManager.AddSprite("redball.bmp", "other content manager"); // case sensitive! ``` -------------------------------- ### Configure Multiple Cameras and Mouse Interaction in FlatRedBall Source: https://docs.flatredball.com/flatredball/api/flatredball/input/mouse/ison3d This C# code demonstrates how to set up two cameras for split-screen viewing and handle mouse interaction. It initializes cameras, adds them to the SpriteManager, and updates sprite color based on mouse position over the sprite and camera viewport. Requires FlatRedBall.Graphics and FlatRedBall.Input namespaces. ```csharp using FlatRedBall.Graphics; using FlatRedBall.Input; // ... inside class scope ... Text text; Sprite sprite; // ... inside Initialize method after initializing FlatRedBall ... IsMouseVisible = true; SpriteManager.Camera.SetSplitScreenViewport(Camera.SplitScreenViewport.LeftHalf); Camera camera = new Camera(); SpriteManager.Cameras.Add(camera); camera.SetSplitScreenViewport(Camera.SplitScreenViewport.RightHalf); camera.Z = 20; sprite = SpriteManager.AddSprite("redball.bmp"); sprite.ColorOperation = ColorOperation.Add; // ... inside Update method ... foreach (Camera camera in SpriteManager.Cameras) { // The following method is only available in June 2008 and newer if (InputManager.Mouse.IsOn(camera)) { if (InputManager.Mouse.IsOn3D(sprite, false, camera)) { sprite.Blue = 1; } } } ``` -------------------------------- ### Sprite Creation and TextureScale Example (C#) Source: https://docs.flatredball.com/flatredball/api/flatredball/sprite/texturescale This example demonstrates how to create two Sprites, set their TextureScale to 1, and position them. When TextureScale is the same for multiple Sprites, their relative sizes will match the relative sizes of their respective Textures. ```csharp Sprite ball = SpriteManager.AddSprite("redball.bmp"); ball.TextureScale = 1; ball.Y = 100; Sprite logo = SpriteManager.AddSprite(@"Assets\Scenes\frblogo.png"); logo.TextureScale = 1; logo.Y = 200; ``` -------------------------------- ### Load BitmapFont via Content Pipeline (C#) Source: https://docs.flatredball.com/flatredball/api/flatredball/graphics/bitmapfont Loads a BitmapFont after processing through the Content Pipeline. This method is recommended for managing texture assets. The .fnt file is copied directly, while the texture is built by the pipeline. Ensure the 'Content' folder structure is correct. ```csharp using FlatRedBall.Graphics; // ... wherever you are loading your font ... BitmapFont bitmapFont = new BitmapFont( @"Content\CustomFont", // No extension since it's been run through the content pipeline @"Content\CustomFont.fnt", // Use extension here since it's simply copied straight over FlatRedBallServices.GlobalContentManager); ``` -------------------------------- ### Get Random Float (0 to 1, Scaled) Source: https://docs.flatredball.com/flatredball/api/flatredball/flatredballservices/random Utilizes the standard .NET Random.NextDouble() method to get a random float between 0 and 1, which can then be scaled to any desired range. This provides fine-grained control over float generation. ```csharp // Gets a number between 0 and 100... float randomNumber = (float)FlatRedBallServices.Random.NextDouble() * 100; // ...which may be used to position an object: MyCharacter.X = randomNumber; ``` -------------------------------- ### CollideAgainstMoveSoft Example with AxisAlignedRectangles Source: https://docs.flatredball.com/flatredball/api/flatredball/math/geometry/axisalignedrectangle/collideagainstmovesoft Demonstrates how to use CollideAgainstMoveSoft to handle collisions between two AxisAlignedRectangles. This example sets up drag, acceleration, and separation values to control the rectangles' movement and interaction. It assumes the use of Glue and custom activity within a Screen. ```csharp void CustomActivity(bool firstTimeCalled) { // The higher the drag the less time the // rectangles will spend moving when no acceleration // is applied to them: AxisAlignedRectangleInstance1.Drag = 3; AxisAlignedRectangleInstance2.Drag = 3; Keyboard keyboard = InputManager.Keyboard; // Increase acceleration to make the rectangle movement // more responsive, but you may also want to increase // the drag if increasing this: const float acceleration = 400; keyboard.ControlPositionedObjectAcceleration(AxisAlignedRectangleInstance1, acceleration); // Increasing this value makes the rectangles push off // of each other more. Making this a smaller value will // result in the rectangles pushing less and being able to // overlap more. const float separationValue = 25; AxisAlignedRectangleInstance1.CollideAgainstMoveSoft(AxisAlignedRectangleInstance2, 1, 1, separationValue); } ``` -------------------------------- ### Initialize with clearListsBelongingTo Source: https://docs.flatredball.com/flatredball/api/flatredball/positionedobject/initialize Explains the 'clearListsBelongingTo' argument and the potential dangers of setting it to true, which can break object relationships. ```APIDOC ## Initialize(bool clearListsBelongingTo) ### Description Initializes a PositionedObject, with an option to clear its 'ListsBelongingTo' property. Setting `clearListsBelongingTo` to `true` (or using the no-argument version) can lead to issues where the object no longer correctly recognizes its membership in management lists, potentially causing errors when trying to remove it. ### Method `Initialize(bool clearListsBelongingTo)` ### Endpoint N/A (This is a method call within the FlatRedBall engine) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp PositionedObject positionedObjectInstance = new PositionedObject(); SpriteManager.AddPositionedObject(positionedObjectInstance); // DANGER: This will clear the PositionedObject's ListsBelongingTo, breaking its relationship with the SpriteManager. positionedObjectInstance.Initialize(); // This call will likely fail because the object no longer knows it belongs to the SpriteManager. SpriteManager.RemovePositionedObject(positionedObjectInstance); // To avoid this, either initialize before adding to the manager or pass false: // positionedObjectInstance.Initialize(false); ``` ### Response #### Success Response (200) This method does not return a value. #### Response Example N/A ``` -------------------------------- ### Create Regular Sprites in C# for Comparison Source: https://docs.flatredball.com/flatredball/api/flatredball/spritemanager/addzbufferedsprite This code example shows how to create two regular sprites (not Z-buffered) with identical properties to the Z-buffered example. This is provided for comparison to illustrate the difference in overlapping behavior, where regular sprites may overlap incorrectly. ```csharp Texture2D texture = FlatRedBallServices.Load("redball.bmp"); Sprite sprite1 = SpriteManager.AddSprite(texture); sprite1.X = -2; sprite1.Y = 6; sprite1.ScaleX = 13; sprite1.ScaleY = 4; sprite1.RotationY = (float)Math.PI / 3.0f; Sprite sprite2 = SpriteManager.AddSprite(texture); sprite2.X = 2; sprite2.Y = 6; sprite2.ScaleX = 13; sprite2.ScaleY = 4; sprite2.RotationY = -(float)Math.PI / 3.0f; ``` -------------------------------- ### Custom Dialog Advance Predicate (C#) Source: https://docs.flatredball.com/flatredball/api/flatredball-forms/controls/games/dialogbox This example defines a custom predicate to advance the DialogBox on a secondary mouse click. Assigning 'AdvancePageInputPredicate' overrides all default input handling, allowing for custom logic. Note that this specific example advances dialog regardless of cursor position. ```csharp void CustomInitialize() { Forms.DialogBoxInstance.AdvancePageInputPredicate = AdvanceOnSecondaryClick; } private bool AdvanceOnSecondaryClick() { return GuiManager.Cursor.SecondaryClick; } ``` -------------------------------- ### Create a Full Code File with CodeDocument Source: https://docs.flatredball.com/flatredball/api/glue-runtime-api/codegeneration/icodeblock Illustrates how to generate a complete code file from scratch using the CodeDocument class, which implements ICodeBlock. This example shows creating using directives, a class definition, a property with get/set accessors, and a method. The final output is a string representing the entire C# file. ```csharp var document = new CodeDocument(); document.Line("using System;"); document.Line("using System.Collections.Generic;"); document.Line("using System.Linq;"); var classBlock = document.Class("public", "MyClass"); classBlock.Line("int health;"); classBlock.Property("public int", "Health") .Get() .Line("return health;") .End() .Set() .Line("health = value;") .Line("ReactToHealthChanged();") .End(); var methodBlock = classBlock.Function("private void", "ReactToHealthChanged"); methodBlock.Line("Console.WriteLine(\"Health changed to \" + health);"); var entireFile = document.ToString(); // do something with entireFile, like save it to disk ``` ```csharp using System; using System.Collections.Generic; using System.Linq; public class MyClass { int health; public int Health { get { return health; } set { health = value; ReactToHealthChanged(); } } public void ReactToHealthChanged() { Console.WriteLine("Health changed to " + health); } } ``` -------------------------------- ### Move to a Screen by Fully Qualified Name (C#) Source: https://docs.flatredball.com/flatredball/api/flatredball/screens/screen/movetoscreen This example shows how to navigate to a new screen using its fully qualified name as a string argument to the MoveToScreen method. This approach is useful when the screen type might not be directly accessible or when referencing screens from different namespaces. The method handles the destruction of the current screen and the loading of the target screen. ```csharp this.MoveToScreen("YourProject.Screens.Level2"); ``` -------------------------------- ### Set and Get Velocity Components in C# Source: https://docs.flatredball.com/flatredball/api/flatredball/positionedobject/velocity Demonstrates how to set and get individual X, Y, and Z components of an object's Velocity in C#. This allows for fine-grained control over movement along each axis. It shows both direct property access (e.g., Velocity.X) and dedicated component properties (e.g., XVelocity). ```csharp this.Velocity.X = 3; // or set the XVelocity property: this.XVelocity = 3; ``` ```csharp // check the value on Velocity... bool isFalling = this.Velocity.Y < 0; // or check the YVelocity property bool isFalling = this.YVelocity < 0; ``` -------------------------------- ### Calling Factory.CreateNew or Variant.CreateNew in CustomInitialize Source: https://docs.flatredball.com/flatredball/api/gluecontrol/instance-creation Demonstrates how to create new entity instances by calling Factory.CreateNew or Variant.CreateNew within the CustomInitialize method. This is a common pattern for initializing entities programmatically. ```csharp public void CustomInitialize() { // Example of creating a new instance using a factory var myEntity = MyEntityFactory.CreateNew(); // Example of creating a new variant instance var myVariantEntity = MyVariantEntityFactory.CreateNew(); } ``` -------------------------------- ### Get Sprite Bottom Edge Coordinate (C#) Source: https://docs.flatredball.com/flatredball/api/flatredball/sprite/bottom This C# code snippet demonstrates how to use the 'Bottom' property to get the absolute Y coordinate of a Sprite's bottom edge. It then uses this value to position a circle. This functionality is useful for aligning or positioning other elements relative to a sprite's boundaries. ```csharp Circle topCircle = ShapeManager.AddCircle(); topCircle.Radius = 16; topCircle.Y = LogoSprite.Top; Circle bottomCircle = ShapeManager.AddCircle(); bottomCircle.Radius = 16; bottomCircle.Y = LogoSprite.Bottom; Circle leftCircle = ShapeManager.AddCircle(); leftCircle.Radius = 16; leftCircle.X = LogoSprite.Left; Circle rightCircle = ShapeManager.AddCircle(); rightCircle.Radius = 16; rightCircle.X = LogoSprite.Right; ``` -------------------------------- ### Create Default SwapChain (C#) Source: https://docs.flatredball.com/flatredball/api/flatredball/graphics/postprocessing/swapchain Creates an automatically managed SwapChain with two render targets. This is the simplest way to set up a SwapChain for post-processing. ```csharp Renderer.CreateDefaultSwapChain(); ``` -------------------------------- ### IPositionedSizedObject Methods Source: https://docs.flatredball.com/flatredball/api/gum-runtime-api/renderinglibrary/ipositionedsizedobject Details on methods available for IPositionedSizedObject, including getting absolute position coordinates. ```APIDOC ## IPositionedSizedObject Methods ### Description This section details the methods available for the IPositionedSizedObject interface, which is the base interface for all visual objects in the RenderingLibrary. ### GetAbsoluteX #### Description Gets the absolute X coordinate of the object. #### Method GET #### Endpoint /websites/flatredball_flatredball_api/RenderingLibrary/IPositionedSizedObject/GetAbsoluteX ### GetAbsoluteY #### Description Gets the absolute Y coordinate of the object. #### Method GET #### Endpoint /websites/flatredball_flatredball_api/RenderingLibrary/IPositionedSizedObject/GetAbsoluteY ``` -------------------------------- ### Get Position Along Spline at Constant Velocity (Newer API) Source: https://docs.flatredball.com/flatredball/api/flatredball/math/splines/spline/getpositionatlengthalongspline This C# code snippet shows how to get the position of an object along a Spline at a constant velocity using the GetPositionAtLengthAlongSpline method. It calculates the desired distance traveled based on current game time and a desired velocity, then directly retrieves the position. ```csharp // ... inside Update method ... float desiredVelocity = 2; // increase to go faster float distanceTraveled = (float)TimeManager.CurrentTime * desiredVelocity; // Else if using April 2010 or newer, one function does it all mCircle.Position = mSpline.GetPositionAtLengthAlongSpline(distanceTraveled); ``` -------------------------------- ### Load Enemy Static Content in Custom Code (C#) Source: https://docs.flatredball.com/flatredball/api/glue-runtime-api/glue-reference-code-customloadstaticcontent Illustrates loading static content for an 'Enemy' Entity type within a custom loading method. This ensures that all necessary content for enemies is loaded when the screen is initialized, preventing potential game freezes or frame rate drops. ```csharp // Inside GameScreen's CustomLoadStaticContent method Enemy.LoadStaticContent(contentManagerName); ``` -------------------------------- ### Size Sprite to Fill Screen using Camera Edges (C#) Source: https://docs.flatredball.com/flatredball/api/flatredball/camera/relativexedgeat This code snippet demonstrates how to add a sprite and then scale it to perfectly fit the camera's view. It utilizes `RelativeXEdgeAt` and `RelativeYEdgeAt` to calculate the necessary scale based on the sprite's Z position relative to the camera. ```csharp Sprite sprite = SpriteManager.AddSprite("redball.bmp"); sprite.X = SpriteManager.Camera.X; sprite.Y = SpriteManager.Camera.Y; sprite.ScaleX = SpriteManager.Camera.RelativeXEdgeAt(sprite.Z); sprite.ScaleY = SpriteManager.Camera.RelativeYEdgeAt(sprite.Z); ``` -------------------------------- ### PropertyCollection Type Strictness Example (C#) Source: https://docs.flatredball.com/flatredball/api/flatredball/instructions/reflection/propertycollection Illustrates the strict type requirements when adding values to a PropertyCollection. Unlike direct code assignments where the compiler might cast types, PropertyCollections require explicit type matching to avoid runtime errors. This example shows the correct way to add a float value for XVelocity. ```csharp // Assuming someSprite is a valid Sprite and propertyCollection is a valid PropertyCollection propertyCollection.Add("XVelocity", 3.0f); // Whew, 3.0f is a float. propertyCollection.ApplyTo(someSprite); // This will now work fine. ``` -------------------------------- ### Set Resolution to Display's Full Resolution (Cautionary Example) Source: https://docs.flatredball.com/flatredball/api/flatredball/graphics/graphicsoptions/setresolution An example of attempting to set the game resolution to the monitor's full width and height. This code snippet highlights a common pitfall where Windows may prevent the game window from fully utilizing the screen height due to title bars and borders. ```csharp FlatRedBallServices.GraphicsOptions.SetResolution(GraphicsDevice.DisplayMode.Width, GraphicsDevice.DisplayMode.Height); ``` -------------------------------- ### Calling IsOn3D Overloads for Text Objects Source: https://docs.flatredball.com/flatredball/api/flatredball/input/mouse/ison3d Demonstrates how to explicitly call both the generic and non-generic versions of the IsOn3D method when checking for mouse interaction with a Text object. The non-generic version is recommended for Text objects. ```csharp // This calls the generic version: InputManager.Mouse.IsOn3D(myText, false); // This calls the non-generic version (the one you should probably call): InputManager.Mouse.IsOn3D(myText, false); ``` -------------------------------- ### Get Position Along Spline at Constant Velocity (Older API) Source: https://docs.flatredball.com/flatredball/api/flatredball/math/splines/spline/getpositionatlengthalongspline This C# code snippet demonstrates how to achieve constant velocity movement along a Spline using older versions of FlatRedBall (March 2010 or earlier). It first converts the desired distance traveled into a time value using GetTimeAtLengthAlongSpline, and then uses that time to get the position. ```csharp // ... inside Update method ... float desiredVelocity = 2; // increase to go faster float distanceTraveled = (float)TimeManager.CurrentTime * desiredVelocity; // If using March 2010 or earlier, convert the length to time double timeOnSpline = mSpline.GetTimeAtLengthAlongSpline(distanceTraveled); // now convert that time to actual position: mCircle.Position = mSpline.GetPositionAtTime(timeOnSpline); ``` -------------------------------- ### Comparing Textures Loaded with Different Content Managers (C#) Source: https://docs.flatredball.com/flatredball/api/flatredball/content/contentmanager Compares texture instances loaded using different, case-sensitive content manager names. The comparison will show that these are distinct instances, highlighting the effect of using different content managers. ```csharp Texture2D firstTexture = SpriteManager.AddSprite("redball.bmp", "Some Content Manager"); Texture2D secondTexture = SpriteManager.AddSprite("redball.bmp", "Other Content Manager"); Texture2D thirdTexture = SpriteManager.AddSprite("redball.bmp", "other content manager"); // case sensitive! if(firstTexture == secondTexture) { // This won't get hit } if(secondTexture == thirdTexture) { // This also won't get hit. } ``` -------------------------------- ### Create Explicit SwapChain and Handle Resize (C#) Source: https://docs.flatredball.com/flatredball/api/flatredball/graphics/postprocessing/swapchain Manually creates a SwapChain and subscribes to the game's resolution change event to update the SwapChain's render target size. This provides more control over the SwapChain's lifecycle. ```csharp Renderer.SwapChain = new FlatRedBall.Graphics.PostProcessing.SwapChain( FlatRedBallServices.Game.Window.ClientBounds.Width, FlatRedBallServices.Game.Window.ClientBounds.Height); FlatRedBallServices.GraphicsOptions.SizeOrOrientationChanged += (_,_) => { Renderer.SwapChain.UpdateRenderTargetSize( FlatRedBallServices.Game.Window.ClientBounds.Width, FlatRedBallServices.Game.Window.ClientBounds.Height); }; ``` -------------------------------- ### Get Absolute File Name using ProjectManager (C#) Source: https://docs.flatredball.com/flatredball/api/glue-plugin-api/flatredball-glue-saveclasses-referencedfilesave This snippet demonstrates how to get the absolute file name of a referenced file within a FlatRedBall Glue project. It utilizes the ProjectManager.MakeAbsolute method, which requires the relative file name and an optional boolean to force interpretation as a content file. This is useful for accessing files regardless of project type. ```csharp bool forceAsContent = true; string absoluteFileName = ProjectManager.MakeAbsolute(namedObjectInstance.Name, forceAsContent); ``` -------------------------------- ### AnimationFrame Texture Source: https://docs.flatredball.com/flatredball/api/flatredball Gets or sets the texture associated with an AnimationFrame. This defines the visual appearance of the frame. ```csharp public Texture Texture { get; set; } ``` -------------------------------- ### Initialize and Control Animations with AnimationController Source: https://docs.flatredball.com/flatredball/api/flatredball/graphics/animation/animationcontroller This C# code demonstrates how to initialize and use an AnimationController to manage different animation states. It sets up three layers: Idle, Running, and Damage, each with its own logic for determining the animation to play based on game state and player direction. The `CustomInitialize` method sets up the controller and layers, while `CustomActivity` calls the controller's activity method each frame. ```csharp AnimationController controller; void CustomInitialize() { // assuming this.Sprite is a valid sprite. The argument tells the controller // what visual object to animate controller = new AnimationController(this.Sprite); // Layers are added in order of low->high priority var idleLayer = controller.AddLayer(); idleLayer.EveryFrameAction = () => { if (this.Direction == Direction.Left) { return "IdleLeft"; } else { return "IdleRight"; } }; var runningLayer = controller.AddLayer(); runningLayer.EveryFrameAction = () => { const float minMovementForWalkAnimation = 1; if (Math.Abs(this.XVelocity) > minMovementForWalkAnimation) { if (this.Direction == Direction.Left) { return "WalkLeft"; } else { return "WalkRight"; } } return null; }; var damageLayer = controller.AddLayer(); damageLayer.EveryFrameAction = () => { if (IsTakingDamage) { if (this.Direction == Direction.Left) { return "TakeDamageLeft"; } else { return "TakeDamageRight"; } } return null; }; } void CustomActivity(bool firstTimeCalled) { controller.Activity(); } ``` -------------------------------- ### Load Content with 'content/' Prefix (C#) Source: https://docs.flatredball.com/flatredball/api/flatredball/flatredballservices/load Shows how to load assets when they are part of an XNA project's Content project. Files must be prefixed with 'content/' regardless of whether they are added as raw files or through the content pipeline. ```csharp // If added as a file: FlatRedBallServices.Load("content/redball.bmp"); // If added through the content pipeline: FlatRedBallServices.Load("content/redball"); ```