### Basic Game Class Setup in Nez Source: https://github.com/prime31/nez/wiki/1.-Getting-Started Demonstrates how to subclass Nez.Core to create a basic game class for a MonoGame project. This sets up the fundamental structure for a Nez application. ```csharp public class Game1 : Core { public Game1() : base( width: 1280, height: 768, isFullScreen: false, enableEntitySystems: false ) {} } ``` -------------------------------- ### Adding Entities to a Nez Scene Source: https://github.com/prime31/nez/wiki/1.-Getting-Started Illustrates how to create entities within a scene and assign them names. This is a core step in organizing game objects that will hold components and logic. ```csharp protected override void Initialize() { base.Initialize(); Window.AllowUserResizing = true; // create our Scene with the DefaultRenderer and a clear color of CornflowerBlue var myScene = Scene.CreateWithDefaultRenderer(Color.CornflowerBlue); // setup our Scene by adding some Entities var entityOne = myScene.CreateEntity("entity-one"); var entityTwo = myScene.CreateEntity("entity-two"); // set the scene so Nez can take over Scene = myScene; } ``` -------------------------------- ### Creating and Setting a Scene in Nez Source: https://github.com/prime31/nez/wiki/1.-Getting-Started Shows how to initialize the game, set window properties, create a scene with a default renderer and clear color, and then assign it to the Nez scene manager. This is the first step in building game content. ```csharp protected override void Initialize() { base.Initialize(); Window.AllowUserResizing = true; // create our Scene with the DefaultRenderer and a clear color of CornflowerBlue var myScene = Scene.CreateWithDefaultRenderer(Color.CornflowerBlue); // set the scene so Nez can take over Scene = myScene; } ``` -------------------------------- ### Adding Components and Textures to Entities in Nez Source: https://github.com/prime31/nez/wiki/1.-Getting-Started Details how to load a texture using the scene's content manager and add it as a Sprite component to entities. It also shows how to position entities within the scene. ```csharp protected override void Initialize() { base.Initialize(); Window.AllowUserResizing = true; // create our Scene with the DefaultRenderer and a clear color of CornflowerBlue var myScene = Scene.CreateWithDefaultRenderer(Color.CornflowerBlue); // load a Texture. Note that the Texture is loaded via the scene.content class. This works just like the standard MonoGame Content class // with the big difference being that it is tied to a Scene. When the Scene is unloaded so too is all the content loaded via myScene.content. var texture = myScene.Content.Load("images/someTexture"); // setup our Scene by adding some Entities var entityOne = myScene.CreateEntity("entity-one"); entityOne.AddComponent(new Sprite(texture)); var entityTwo = myScene.CreateEntity("entity-two"); entityTwo.AddComponent(new Sprite(texture)); // move entityTwo to a new location so it isn't overlapping entityOne entityTwo.Position = new Vector2(200, 200); // set the scene so Nez can take over Scene = myScene; } ``` -------------------------------- ### Start Local Development Server (Yarn) Source: https://github.com/prime31/nez/blob/master/Nez.github.io/README.md Starts a local development server for the website. This command enables live reloading, allowing developers to see changes reflected immediately without restarting the server. ```console yarn start ``` -------------------------------- ### Install Project Dependencies (Yarn) Source: https://github.com/prime31/nez/blob/master/Nez.github.io/README.md Installs the necessary project dependencies using the Yarn package manager. This is a prerequisite for local development and building the website. ```console yarn install ``` -------------------------------- ### Initialize and Toggle ImGuiManager Source: https://github.com/prime31/nez/blob/master/Nez.ImGui/README.md Shows how to register the `ImGuiManager` with Nez and toggle its rendering state. This is the basic setup for using ImGui in the project. ```csharp var imGuiManager = new ImGuiManager(); Core.RegisterGlobalManager( imGuiManager ); // toggle ImGui rendering on/off. It starts out enabled. imGuiManager.SetEnabled( false ); ``` -------------------------------- ### Asynchronous Asset Loading Source: https://github.com/prime31/nez/blob/master/Nez.github.io/docs/features/ContentManagement.md Provides examples of how to asynchronously load single or multiple assets, with a callback for when loading is complete. ```csharp content.LoadAsync( "assetName", (loadedAsset) => { /* callback logic */ } ); ``` ```csharp content.LoadAsync( new string[] { "asset1", "asset2" }, (loadedAssets) => { /* callback logic */ } ); ``` -------------------------------- ### KeyValueDataStore Usage (C#) Source: https://github.com/prime31/nez/blob/master/Nez.Persistence/BINARY_README.md Provides examples for using the KeyValueDataStore to manage small key-value pairs. This includes loading, setting, getting, checking for, and deleting data, as well as flushing changes to a file. ```csharp // fetch the FileDataStore from your service container var fileDataStore = Core.services.GetOrAddService(); // load data KeyValueDataStore.Load( fileDataStore ); // setting data KeyValueDataStore.Default.Set( "the-key", true ); // values can be of type string, bool, int or float. // getting data var data = KeyValueDataStore.Default.GetBool( "the-key" ); var data = KeyValueDataStore.Default.GetBool( "the-key", false ); // specifying a default value if the key isnt present // checking for existence of a key if( KeyValueDataStore.Default.ContainsBoolKey( "the-key" ) ) // do something // deleting a keys data KeyValueDataStore.Default.DeleteBoolKey( "the-key" ); // saving data KeyValueDataStore.Flush( fileDataStore ); ``` -------------------------------- ### Deferred Sprite Material Setups in C# Source: https://github.com/prime31/nez/blob/master/Nez.github.io/docs/features/Graphics/Lighting/DeferredLighting.md Demonstrates three common material setups for deferred lighting: standard normal-mapped lit, diffuse-only, and normal-mapped lit with self-illumination. It shows how to create DeferredSpriteMaterial instances and configure self-illumination properties. ```csharp // lit, normal mapped Material. normalMapTexture is a reference to the Texture2D that contains your normal map. var standardMaterial = new DeferredSpriteMaterial( normalMapTexture ); // diffuse lit Material. The NullNormalMapTexture is used var diffuseOnlylMaterial = new DeferredSpriteMaterial( deferredRenderer.NullNormalMapTexture ); // lit, normal mapped and self illuminated Material. // first we create the Material with our normal map. Note that your normal map should have an alpha channel for the self illumination and it // needs to have premultiplied alpha disabled var selfLitMaterial = new DeferredSpriteMaterial( selfLitNormalMapTexture ); // we can access the Effect on a Material via the `TypedEffect` property. We need to tell the Effect that we want self illumination and // optionally set the self illumination power. selfLitMaterial.effect.SetUseNormalAlphaChannelForSelfIllumination( true ) .SetSelfIlluminationPower( 0.5f ); ``` -------------------------------- ### Deferred Lighting Scene Setup in C# Source: https://github.com/prime31/nez/blob/master/Nez.github.io/docs/features/Graphics/Lighting/DeferredLighting.md Illustrates how to set up a scene for deferred lighting by adding a DeferredLightingRenderer. It shows how to specify render layers for lights and sprites, and how to optionally set ambient lighting. ```csharp // define your renderLayers somewhere easy to access const int LIGHT_LAYER = 1; const int OBJECT_LAYER1 = 10; const int OBJECT_LAYER2 = 20; // add the DeferredLightingRenderer to your Scene specifying which renderLayer contains your lights and an arbitrary number of renderLayers for it to render var deferredRenderer = AddRenderer(new DeferredLightingRenderer(0, LIGHT_LAYER, OBJECT_LAYER1, OBJECT_LAYER2)); // optionally set ambient lighting deferredRenderer.SetAmbientColor(Color.Gray); ``` -------------------------------- ### Setup and Use Virtual Input in C# Source: https://github.com/prime31/nez/blob/master/FAQs/Nez-Core.md Demonstrates how to set up and use virtual input classes in C# to map multiple input sources (keyboard keys, gamepad buttons, analog sticks) to single actions or axes. This allows for flexible control schemes. ```csharp void SetupVirtualInput() { // setup input for shooting a fireball. we will allow z on the keyboard or a on the gamepad _fireInput = new VirtualButton(); _fireInput.AddKeyboardKey( Keys.X ) .AddGamePadButton( 0, Buttons.A ); // horizontal input from dpad, left stick or keyboard left/right _xAxisInput = new VirtualIntegerAxis(); _xAxisInput.AddGamePadDPadLeftRight() .AddGamePadLeftStickX() .AddKeyboardKeys( VirtualInput.OverlapBehavior.TakeNewer, Keys.Left, Keys.Right ); // vertical input from dpad, left stick or keyboard up/down _yAxisInput = new VirtualIntegerAxis(); _yAxisInput.AddGamePadDpadUpDown() .AddGamePadLeftStickY() .AddKeyboardKeys( VirtualInput.OverlapBehavior.TakeNewer, Keys.Up, Keys.Down ); } void IUpdatable.Update() { // gather input from the Virtual Inputs we setup above var moveDir = new Vector2( _xAxisInput.Value, _yAxisInput.Value ); var isShooting = _fireInput.IsPressed; } ``` -------------------------------- ### Custom Transition Example Source: https://github.com/prime31/nez/blob/master/Nez.github.io/docs/features/ECS/SceneTransitions.md An example of a custom scene transition using an Effect for visual transitions. ```APIDOC ## Creating Custom Transitions The `SceneTransition` class allows for the creation of custom transitions by subclassing it. Transitions can be one-part (obscure screen, load scene, transition effect) or two-part (transition effect, load scene, display new scene). ### Key Methods to Override: * **Constructor**: Load any necessary `Effect`s. * **OnBeginTransition**: Coroutine that handles the transition logic. Use `_isNewSceneLoaded` flag for two-part transitions. * Perform the first part of the transition (optional, for two-part). * `yield return Core.StartCoroutine( LoadNextScene() )` to load the next scene. * Perform the transition effect. * Call `TransitionComplete()` to finish and clean up. * Unload used Effects/Textures or do it in `TransitionComplete`. * **Render**: Called every frame to control the final render output. Use `previousSceneRender` to access the previous scene's render. ### Helper Method: * **TickEffectProgressProperty**: A helper to animate an `Effect`'s progress from 0 to 1 or 1 to 0 within a coroutine. ### Example: SuperTransition This example demonstrates a custom transition using an `Effect`: ```csharp public class SuperTransition : SceneTransition { public float Duration = 1f; public EaseType EaseType = EaseType.QuartOut; Effect _effect; Rectangle _destinationRect; public SuperTransition( Func sceneLoadAction ) : base( sceneLoadAction, true ) { _destinationRect = previousSceneRender.Bounds; _effect = Core.content.loadEffect( "TransitionEffect.mgfxo" ); } public override IEnumerator OnBeginTransition() { yield return Core.StartCoroutine( LoadNextScene() ); yield return Core.StartCoroutine( TickEffectProgressProperty( _effect, duration, easeType ) ); TransitionComplete(); Core.Content.UnloadEffect( _effect ); } public override void Render( Batcher batcher ) { Core.graphicsDevice.SetRenderTarget( null ); batcher.Begin( BlendState.NonPremultiplied, Core.DefaultSamplerState, DepthStencilState.None, null, _effect ); batcher.Draw( previousSceneRender, _destinationRect, Color.White ); bbatcher.End(); } } ``` ``` -------------------------------- ### Content Path Generation Example (C#) Source: https://github.com/prime31/nez/blob/master/FAQs/ContentManagement.md Demonstrates using the ContentPathGenerator to access content with compile-time safety. Instead of using strings, it leverages generated static class members. ```csharp // before using the ContentPathGenerator you have strings to represent your content var tex = content.Load( "Textures/Scene1/blueBird" ); // after using the ContentPathGenerator you will have compile-tile safety for your content var tex = content.Load( Nez.Content.Textures.Scene1.blueBird ); ``` -------------------------------- ### Deferred Lighting Material Setup (C#) Source: https://github.com/prime31/nez/blob/master/FAQs/lang.cn_wip/DeferredLighting.md Demonstrates how to set up different materials for deferred lighting. Includes standard lit materials, diffuse-only materials, and self-illuminated materials using normal maps with alpha channels. Requires Nez engine and Texture2D objects. ```csharp // 光照, 法线贴图 Material(lit, normal mapped Material). normalMapTexture 是你法线贴图 Texture2D 类型的引用 var standardMaterial = new DeferredSpriteMaterial( normalMapTexture ); // 漫反射光照 Material. 使用 NullNormalMapTexture. var diffuseOnlylMaterial = new DeferredSpriteMaterial( deferredRenderer.NullNormalMapTexture ); // 带光照, 法线贴图和自照明的 Material // (lit, normal mapped and self illuminated Material.) // 首先我们需要用我们的法线贴图创建一个 Material. 注意你的法线贴图需要有 alpha 通道给自照明使用 // 需要把预乘 alpha 值关闭 var selfLitMaterial = new DeferredSpriteMaterial( selfLitNormalMapTexture ); // 我们可以通过 Material 的 `TypedEffect` 来访问 Effect. 我们需要告诉 Effect 我们需要自照明并且可选的调整它的强度 selfLitMaterial.effect.SetUseNormalAlphaChannelForSelfIllumination( true ) .SetSelfIlluminationPower( 0.5f ); ``` -------------------------------- ### Sprite Atlas Packer Usage Example Source: https://github.com/prime31/nez/blob/master/Nez.SpriteAtlasPacker/README.md Demonstrates the basic command-line usage of the SpriteAtlasPacker.exe tool to pack images from a folder into an output atlas image and map file, specifying frame rate for animations. ```bash mono SpriteAtlasPacker.exe -image:out.png -map:out.atlas -fps:7 folder/with/images ``` -------------------------------- ### Deferred Lighting Material Setups (C#) Source: https://github.com/prime31/nez/blob/master/FAQs/DeferredLighting.md Demonstrates how to set up different materials for deferred lighting, including standard normal-mapped, diffuse-only, and self-illuminated materials. Assumes normal maps are created and premultiplied alpha is disabled for self-illumination. ```csharp var standardMaterial = new DeferredSpriteMaterial( normalMapTexture ); ``` ```csharp var diffuseOnlylMaterial = new DeferredSpriteMaterial( deferredRenderer.NullNormalMapTexture ); ``` ```csharp var selfLitMaterial = new DeferredSpriteMaterial( selfLitNormalMapTexture ); selfLitMaterial.effect.SetUseNormalAlphaChannelForSelfIllumination( true ) .SetSelfIlluminationPower( 0.5f ); ``` -------------------------------- ### Basic Verlet Physics Setup in Nez Source: https://github.com/prime31/nez/blob/master/FAQs/Verlet.md Demonstrates how to initialize and update a Nez verlet physics world using a custom component. It includes adding built-in composites like Tire and Cloth and utilizing the debug rendering system. ```csharp public class VerletDemo : RenderableComponent, IUpdatable { public override float Width { get { return 800; } } public override float Height { get { return 600; } } World _world; public override void OnAddedToEntity() { // create the verlet world which handles simulation _world = new World( new Rectangle( 0, 0, 800, 600 ) ); // add a couple built-in Composite objects _world.AddComposite( new Tire( new Vector2( 100, 100 ), 50, 20 ) ); _world.AddComposite( new Cloth( new Vector2( 10, 10 ), 200, 100 ) ); } public void Update() { _world.Update(); } public override void Render( Batcher batcher, Camera camera ) { _world.DebugRender( batcher ); } } ``` -------------------------------- ### Create and Start a Basic Position Tween Source: https://github.com/prime31/nez/blob/master/Nez.github.io/docs/features/Utils/Tweening.md Demonstrates creating a simple Entity and then tweening its position to a new Vector2 over a specified duration. The tween is started immediately. ```csharp Entity tweenTargetEntity = CreateEntity("tweenTarget"); tweenTargetEntity.Position = new Vector2(100, 100); tweenTargetEntity.AddComponent( new PrototypeSpriteRenderer(10,10) {Color = Color.Yellow }); tweenTargetEntity .TweenPositionTo(new Vector2(250, 250), 5f) .Start(); ``` -------------------------------- ### Deferred Lighting Scene Setup (C#) Source: https://github.com/prime31/nez/blob/master/FAQs/DeferredLighting.md Illustrates how to add and configure the DeferredLightingRenderer to a scene. This involves specifying render layers for lights and sprite objects, and optionally setting ambient lighting. ```csharp // define your renderLayers somewhere easy to access const int LIGHT_LAYER = 1; const int OBJECT_LAYER1 = 10; const int OBJECT_LAYER2 = 20 // add the DeferredLightingRenderer to your Scene specifying which renderLayer contains your lights and an arbitrary number of renderLayers for it to render var deferredRenderer = scene.AddRenderer( new DeferredLightingRenderer( 0, LIGHT_LAYER, OBJECT_LAYER1, OBJECT_LAYER2 ) ); // optionally set ambient lighting deferredRenderer.SetAmbientColor( Color.Black ); ``` -------------------------------- ### Entity Setup for Deferred Lighting (C#) Source: https://github.com/prime31/nez/blob/master/FAQs/lang.cn_wip/DeferredLighting.md Sets up entities with sprites, assigning them to specific render layers and materials. Also demonstrates creating entities with point lights, ensuring they are on the correct light layer. Requires Nez engine, SpriteTexture, and Color objects. ```csharp // 创建一个包含 sprite 的实体 var entity = Scene.CreateEntity( "sprite" ); // 加入一个 sprite, 这里还有个重要的部分: 确保设置 RenderLayer 和 Material. entity.AddComponent( new Sprite( spriteTexture ) ) .SetRenderLayer( OBJECT_LAYER1 ) .SetMaterial( standardMaterial ); // 创建一个没有设置 Material 的 Entity. 它会使用默认仅漫反射的 DeferredLightingRenderer.Material scene.CreateEntity( "diffuse-only" ) .AddComponent( new Sprite( spriteTexture ) ) .SetRenderLayer( OBJECT_LAYER1 ); // 创建一个包含我们点光源的 Entity var lightEntity = scene.CreateEntity( "point-light" ); // 加入一个点光源组件然后确保 RenderLayer 是在光照层(LIGHT_LAYER)上! lightEntity.AddComponent( new PointLight( Color.Yellow ) ) .SetRenderLayer( LIGHT_LAYER ); ``` -------------------------------- ### Perform a Linecast Source: https://github.com/prime31/nez/blob/master/FAQs/lang.cn_wip/Physics.md Example of casting a line from a start point to an end point to detect the first collider hit based on a layerMask. Useful for checking visibility or environmental interactions. ```csharp var hit = Physics.Linecast( start, end ); if( hit.Collider != null ) Debug.Log( "ray hit {0}, entity: {1}", hit, hit.collider.entity ) ``` -------------------------------- ### Switch Nez Projects to .NET Standard 2.0 (Shell) Source: https://github.com/prime31/nez/blob/master/Nez.github.io/docs/getting-started/installation.md This shell command, intended for Linux or compatible environments like the Windows Subsystem for Linux, recursively finds and modifies Nez project files (.csproj) to target .NET Standard 2.0 instead of .NET Framework 4.7.1. It excludes test projects and pipeline tool projects. ```bash find . -path Tests -prune -o -name 'Nez*.csproj' | grep -v Tests | grep -v Pipeline | xargs perl -pi -e 's/net471/netstandard2.0/g' ``` -------------------------------- ### Start Scene Transition with WindTransition (C#) Source: https://github.com/prime31/nez/blob/master/FAQs/SceneTransitions.md Loads a new scene with a WindTransition effect. Requires a Func to specify the target scene. ```csharp Core.StartSceneTransition( new WindTransition( () => new YourNextScene() ) ); ``` -------------------------------- ### Breadth First Search with String Nodes Source: https://github.com/prime31/nez/blob/master/FAQs/Pathfinding.md Demonstrates using Breadth First Search for pathfinding with a graph where nodes are represented by strings. This example shows how to create an UnweightedGraph, add nodes and edges, and then find a path between two string nodes. ```csharp var graph = new UnweightedGraph(); graph.AddEdgesForNode( "a", new string[] { "b" } ); // a→b graph.AddEdgesForNode( "b", new string[] { "a", "c", "d" } ); // b→a, b→c, b→d graph.AddEdgesForNode( "c", new string[] { "a" } ); // c→a graph.AddEdgesForNode( "d", new string[] { "e", "a" } ); // d→e, d→a graph.AddEdgesForNode( "e", new string[] { "b" } ); // e→b var path = BreadthFirstPathfinder.Search( graph, "c", "e" ); ``` -------------------------------- ### Start Coroutine in Nez Source: https://github.com/prime31/nez/blob/master/Nez.github.io/docs/about/introduction.md Initiates a coroutine for asynchronous tasks or animations. This is a core feature for managing operations over multiple frames. ```csharp Core.startCoroutine(yourCoroutineMethod()); ``` -------------------------------- ### Demonstrate Object Pooling Usage with Trees in C# Source: https://github.com/prime31/nez/blob/master/Nez.github.io/docs/features/Utils/Pooling.md Provides a C# example demonstrating the creation and usage of the SomeTree class, which leverages Nez's object pooling. It shows how nodes are instantiated, reused, and how the pool manages object lifecycles. ```cs SomeTree firstTree = new SomeTree(); firstTree.Add(3); firstTree.Add(2); firstTree.Add(4); firstTree.Add(5); firstTree.Add(1); string firstResult = firstTree.ToString(); // "1,2,5,4,3" System.Console.WriteLine(SomeNode.InstanceCount); // 5 // Free Nodes to pool firstTree.Clear(); SomeTree secondTree = new SomeTree(); secondTree.Add(8); secondTree.Add(7); secondTree.Add(4); secondTree.Add(2); secondTree.Add(3); string secondResult = secondTree.ToString(); // "3,2,4,7,8" System.Console.WriteLine(SomeNode.InstanceCount); // 5 ``` -------------------------------- ### Setup Nez Entities with SpriteRenderer and PointLight Source: https://github.com/prime31/nez/blob/master/Nez.github.io/docs/features/Graphics/Lighting/DeferredLighting.md This C# code snippet demonstrates creating entities in the Nez framework. It shows how to initialize a DeferredSpriteMaterial with a normal map, create a sprite entity with a SpriteRenderer, and set its render layer and material. It also illustrates creating a point-light entity with a MouseFollow component and a PointLight component, setting its intensity and render layer. ```csharp var standardMaterial = new DeferredSpriteMaterial(normalMapTexture); var entity = CreateEntity("sprite"); entity.AddComponent(new SpriteRenderer(spriteTexture)) .SetRenderLayer(OBJECT_LAYER1) .SetMaterial(standardMaterial); entity.Transform.Position = Screen.Center; var lightEntity = CreateEntity("point-light"); lightEntity .AddComponent(new MouseFollow()); lightEntity.AddComponent(new PointLight(Color.White).SetIntensity(0.8f)) .SetRenderLayer(LIGHT_LAYER); ``` -------------------------------- ### Custom SuperTransition Example in C# Source: https://github.com/prime31/nez/blob/master/FAQs/SceneTransitions.md A C# example of a custom scene transition named SuperTransition that utilizes a shader effect for visual transitions. It inherits from SceneTransition and overrides OnBeginTransition and Render methods to manage the transition process and rendering. ```csharp public class SuperTransition : SceneTransition { /// /// duration for the transition /// public float Duration = 1f; /// /// ease equation to use for the animation /// public EaseType EaseType = EaseType.QuartOut; Effect _effect; Rectangle _destinationRect; /// /// constructor. Note that sceneLoadAction can be null for intra-Scene transitions and everything will still work as expected. /// public SuperTransition( Func sceneLoadAction ) : base( sceneLoadAction, true ) { // store off the bounds of the scene render so we can display it in the render method _destinationRect = previousSceneRender.Bounds; // load the Effect _effect = Core.content.loadEffect( "TransitionEffect.mgfxo" ); } public override IEnumerator OnBeginTransition() { // load up the new Scene. If sceneLoadAction is null this will just set the _isNewSceneLoaded flag to true. yield return Core.StartCoroutine( LoadNextScene() ); // use our Effect to the transition to the new Scene. This call will tick the _progress EffectParameter from 0 to 1 with our // custom EaseType for extra control. yield return Core.StartCoroutine( TickEffectProgressProperty( _effect, duration, easeType ) ); // call through to let SceneTransition know we are all done and it can clean itself up and stop calling render TransitionComplete(); // cleanup our Effect since we are done with it Core.Content.UnloadEffect( _effect ); } public override void Render( Batcher batcher ) { // here, we are just going to render directly to the back buffer using our Effect. We render the previousSceneRender which // SceneTransition gets for us. It contains the last render of the previous Scene. Core.graphicsDevice.SetRenderTarget( null ); batcher.Begin( BlendState.NonPremultiplied, Core.DefaultSamplerState, DepthStencilState.None, null, _effect ); batcher.Draw( previousSceneRender, _destinationRect, Color.White ); bbatcher.End(); } } ``` -------------------------------- ### Start Intra-Scene Transition with SquaresTransition (C#) Source: https://github.com/prime31/nez/blob/master/Nez.github.io/docs/features/ECS/SceneTransitions.md Shows how to perform an intra-scene transition using the SquaresTransition. It also illustrates how to hook into the `OnScreenObscured` event for custom actions during the transition. ```csharp var transition = new SquaresTransition(); // for intra-Scene transitions we will probably be interested in knowing when the screen is obscured so we can take action transition.OnScreenObscured = MyOnScreenObscuredMethod; Core.StartSceneTransition( transition ); void MyOnScreenObscuredMethod() { // move Camera to new location // reset Entities } ``` -------------------------------- ### Setup Lightmap Renderer Source: https://github.com/prime31/nez/blob/master/Nez.github.io/docs/features/Graphics/Lighting/SpriteLights.md Configures a renderer specifically for the lightmap, assigning a RenderTexture and a clear color for ambient lighting. This renderer is crucial for the SpriteLights technique. ```csharp RenderLayerRenderer lightRenderer = AddRenderer(new RenderLayerRenderer(-1, SpriteLightRenderLayer)); lightRenderer.RenderTexture = new RenderTexture(); lightRenderer.RenderTargetClearColor = new Color(10, 10, 10, 255); ``` -------------------------------- ### Gamepad Navigation Setup in C# Source: https://github.com/prime31/nez/blob/master/Nez.github.io/docs/features/UI/NezUI.md Illustrates how to configure gamepad navigation for UI elements in Nez. It shows how to enable explicit focus control, define directional navigation between elements (buttons and sliders), and set up wrapping for navigation. This is crucial for making UI elements responsive to gamepad input. ```csharp // create buttons and a slider... // be sure to enable explicit control on each Element! leftButton.ShouldUseExplicitFocusableControl = true; // when pressing right change control to the middleSlider leftButton.GamepadRightElement = middleSlider; // optional. This would make pressing left wrap around to the rightButton leftButton.GamepadLeftElement = rightButton; middleSlider.ShouldUseExplicitFocusableControl = true; middleSlider.GamepadLeftElement = leftButton; middleSlider.GamepadRightElement = rightButton; rightButton.ShouldUseExplicitFocusableControl = true; rightButton.GamepadLeftElement = middleSlider; // optional. This would make pressing right wrap around to the leftButton rightButton.GamepadRightElement = leftButton; ``` -------------------------------- ### Deferred Lighting Scene Setup (C#) Source: https://github.com/prime31/nez/blob/master/FAQs/lang.cn_wip/DeferredLighting.md Configures the scene with a DeferredLightingRenderer. This involves specifying render layers for lighting and objects, and optionally setting ambient light color. Requires Nez engine and Color objects. ```csharp // 定义你的 RenderLayers, 这样你会方便访问一些 const int LIGHT_LAYER = 1; const int OBJECT_LAYER1 = 10; const int OBJECT_LAYER2 = 20 // 加入 DeferredLightingRenderer 到你的场景里, 然后指定相应的 RenderLayer 和一堆你希望渲染到的 RenderLayers var deferredRenderer = scene.AddRenderer( new DeferredLightingRenderer( 0, LIGHT_LAYER, OBJECT_LAYER1, OBJECT_LAYER2 ) ); // (可选的) 设置环境光照 deferredRenderer.SetAmbientColor( Color.Black ); ``` -------------------------------- ### Link Default Content for .NET Core Projects (XML) Source: https://github.com/prime31/nez/blob/master/Nez.github.io/docs/getting-started/installation.md This XML snippet configures project references to link default Nez content files, such as effects and textures, into your Monogame project for .NET Core. It specifies linking paths and ensures files are copied to the output directory. ```xml Content\nez\effects\%(RecursiveDir)%(Filename)%(Extension) PreserveNewest Content\nez\textures\%(RecursiveDir)%(Filename)%(Extension) PreserveNewest Content\nez\NezDefaultBMFont.xnb PreserveNewest ``` -------------------------------- ### Simple PostProcessor Example in C# Source: https://github.com/prime31/nez/blob/master/FAQs/Rendering.md Demonstrates a basic PostProcessor that composites a RenderTexture with the rest of the scene, applying an effect. It takes a RenderTexture and an Effect as input and overrides the Process method to draw the source scene and the specified RenderTexture with the effect. ```cs public class SimplePostProcessor : PostProcessor { RenderTexture _renderTexture; public SimplePostProcessor(RenderTexture renderTexture, Effect effect ) : base( 0 ) { _renderTexture = renderTexture; this.effect = effect; } public override void Process( RenderTarget2D source, RenderTarget2D destination ) { Core.graphicsDevice.SetRenderTarget( destination ); Graphics.instance.spriteBatch.Begin( effect: effect ); // render source contains all of the Scene that was not rendered into _renderTexture Graphics.instance.spriteBatch.Draw( source, Vector2.Zero, Color.White ); // now we render the contents of our _renderTexture on top of it Graphics.instance.spriteBatch.Draw( _renderTexture, Vector2.Zero ); Graphics.instance.spriteBatch.End(); } } ``` -------------------------------- ### C# Adding SimpleMover Component to an Entity Source: https://github.com/prime31/nez/wiki/2.-Creating-Custom-Components Example of how to create an entity and add the custom SimpleMover component to it, along with a Sprite component, in C#. ```csharp var entityOne = myScene.CreateEntity( "entity-one" ); entityOne.AddComponent( new Sprite( texture ) ); entityOne.AddComponent( new SimpleMover() ); ``` -------------------------------- ### C# Mutable ValueTuple Examples Source: https://github.com/prime31/nez/blob/master/Nez.github.io/docs/features/Utils/Collections.md Shows different ways to declare and use mutable ValueTuples in C#, highlighting their value type nature and how they can be modified. ```cs var twoNumbersValueTuple = new ValueTuple(1, 2); twoNumbersValueTuple.Item1 = 3; twoNumbersValueTuple.Item1 = 4; ``` ```cs var twoNumbersValueTuple; twoNumbersValueTuple.Item1 = 3; twoNumbersValueTuple.Item1 = 4; ``` ```cs (int first, int second) twoNumbersValueTuple; twoNumbersValueTuple.first = 3; twoNumbersValueTuple.second = 4; ``` -------------------------------- ### Dijkstra Pathfinding with WeightedGridGraph and TiledMap Source: https://github.com/prime31/nez/blob/master/FAQs/Pathfinding.md Illustrates Dijkstra's algorithm using a WeightedGridGraph in conjunction with a TiledMap. This example shows how to initialize the graph with a TiledMap collision layer, add weighted nodes, and then calculate a path between two points. ```csharp var graph = new WeightedGridGraph( tiledMapCollisionLayer ); graph.WeightedNodes.Add( new Point( 3, 3 ) ); graph.WeightedNodes.Add( new Point( 3, 4 ) ); graph.WeightedNodes.Add( new Point( 4, 3 ) ); graph.WeightedNodes.Add( new Point( 4, 4 ) ); var path = graph.Search( new Point( 3, 4 ), new Point( 15, 17 ) ); ``` -------------------------------- ### Install Nez as a Git Submodule Source: https://github.com/prime31/nez/blob/master/README.md Instructions for integrating Nez into a MonoGame project by adding it as a Git submodule. This involves referencing the Nez project and ensuring necessary content files are copied to the output directory. It also includes a command to restore NuGet packages if needed. ```csharp /// /// Add Nez.Portable/Nez.csproj to your solution and add a reference to it in your main project. /// If you are working with MonoGame 3.8, use Nez.Portable/Nez.MG38.csproj instead. /// public class Game1 : Nez.Core { // Game initialization code here } /// /// Restore NuGet packages if 'project.assets.json' is missing. /// /// msbuild Nez.sln /t:restore ``` -------------------------------- ### C# Immutable Tuple Example Source: https://github.com/prime31/nez/blob/master/Nez.github.io/docs/features/Utils/Collections.md Demonstrates the creation and usage of an immutable Tuple in C#. Tuples are reference types and cannot be modified after creation. ```cs var twoNumbersTuple = new Tuple(1, 2); ``` -------------------------------- ### Nez UI Skin JSON Configuration Source: https://github.com/prime31/nez/blob/master/Nez.github.io/docs/features/UI/NezUI.md Example JSON structure for defining Nez UI skins. It includes definitions for colors, texture atlases, and various UI element styles like buttons, windows, and sliders. ```javascript { // defines colors accessible via skin.getColor. These can also be referenced in actual style definitions below Colors: { green: '#00ff00', orange: '#ff9900', blue: '#0000ff', black: [0, 0, 0, 255], gray: [50, 50, 50, 255], blue: [116, 139, 167, 255], dialogDim: [50, 50, 50, 50] }, // array of any LibGdxAtlases. The path should be the same one you would use to load it via the content system. LibGdxAtlases: [ 'bin/skin/uiskinatlas' ], // array of any TextureAtlases. The path should be the same one you would use to load it via the content system. TextureAtlases: [ 'bin/skin/textureAtlas' ], // the rest of the file is specific style types. The key (ButtonStyle here) is the exact class name from the UI element. ButtonStyle: { // "default" is the name of the style that is used at runtime to find it. Any font, color or IDrawable can be specified. // Nez UI will search any loaded atlases for the specified resource. default: { Down: 'default-round-down', Up: 'default-round' }, toggle: { Down: 'default-round-down', Checked: 'default-round-down', Up: 'default-round' }, // this ButtonStyle uses only references to colors. Nez UI will handle making appropriate resources at runtime for you. colored: { Down: 'gray', Up: 'black', Over: 'blue' } }, SplitPaneStyle: { 'default-vertical': { Handle: 'default-splitpane-vertical' }, 'default-horizontal': { Handle: 'default-splitpane' } }, WindowStyle: { // the titleFontColor directly references a color that we specified above in the colors section default: { TitleFont: 'nez/NezDefaultBMFont', Background: 'default-window', TitleFontColor: 'white' }, dialog: { TitleFont: 'nez/NezDefaultBMFont', Background: 'default-window', TitleFontColor: 'white', StageBackground: 'dialogDim' } }, ProgressBarStyle: { 'default-horizontal': { Background: 'default-slider', Knob: 'default-slider-knob' }, 'default-vertical': { Background: 'default-slider', Knob: 'default-round-large' } }, SliderStyle: { 'default-horizontal': { Background: 'default-slider', Knob: 'default-slider-knob' }, 'default-vertical': { Background: 'default-slider', Knob: 'default-round-large' } }, LabelStyle: { // fonts should be the same path you would use to load it via the content system default: { Font: 'nez/NezDefaultBMFont', FontColor: 'white' }, tooltip: { Font: 'nez/NezDefaultBMFont', FontColor: 'blue' }, }, TextTooltipStyle: { // note that LabelStyle referes the the 'tooltip' LabelStyle defined above default: { LabelStyle: 'tooltip', Background: 'gray' } } } ``` -------------------------------- ### IPersistable Interface Implementation Example (C#) Source: https://github.com/prime31/nez/blob/master/Nez.Persistence/BINARY_README.md Demonstrates how to implement the IPersistable interface for custom classes. This involves defining 'Persist' and 'Recover' methods to handle data serialization and deserialization using provided writer and reader objects. ```csharp public class PersistableExample : IPersistable { public List strings = new List(); public int anInt; public bool? nullableBool; void IPersistable.Persist( IPersistableWriter writer ) { // write out your data. Most types can be written out of the box writer.Write( strings ); writer.Write( anInt ); writer.Write( nullableBool ); } void IPersistable.Recover( IPersistableReader reader ) { // read your data IN THE SAME ORDER YOUR WROTE IT! reader.ReadStringListInto( strings ); anInt = reader.ReadInt(); nullableBool = reader.ReadOptionalBool(); } } // saving the object var myObj = new PersistableExample(); var dataStore = Core.services.GetOrAddService(); dataStore.Save( "the-filename.bin", myObj ); // loading the object. If the file doesn't exist, the Recover method will not be called dataStore.Load( "the-filename.bin", myObj ); ``` -------------------------------- ### Start Coroutine in Nez Source: https://github.com/prime31/nez/blob/master/README.md Initiates a coroutine for managing long tasks or animations across multiple frames. This method is part of the core functionality for asynchronous operations within Nez. ```csharp Core.startCoroutine(myCoroutine()); ``` -------------------------------- ### Create Custom Inspector for a Type Source: https://github.com/prime31/nez/blob/master/Nez.ImGui/README.md Provides an example of creating a custom inspector for a class using `CustomInspectorAttribute`. This allows full control over how a type is rendered in the ImGui inspector, including handling null or creating instances. ```csharp [CustomInspector( typeof( WontShowInInspectorByDefaultInspector ) )] public class WontShowInInspectorByDefault { public string text = "the string"; public float speed = 54; public int index = 10; } class WontShowInInspectorByDefaultInspector : AbstractTypeInspector { public override void drawMutable() { var myObj = getValue(); if( myObj == null ) { if( ImGui.Button( "Create Object" ) ) { myObj = new WontShowInInspectorByDefault(); setValue( myObj ); } } else { ImGui.InputText( "text", ref myObj.text, 50 ); ImGui.DragFloat( "speed", ref myObj.speed ); ImGui.DragInt( "index", ref myObj.index ); } } } ``` -------------------------------- ### Create Dynamic Rigid Body with Circle Collider Source: https://github.com/prime31/nez/blob/master/FAQs/FarseerPhysics.md Demonstrates creating an entity with a dynamic Farseer rigid body and a circle collision shape. It chains component additions for efficient setup. Requires Nez and Farseer physics libraries. ```cs CreateEntity( "circle-sprite" ) .SetPosition( pos ) .SetScale( scale ) .AddComponent() .SetBodyType( BodyType.Dynamic ) .AddComponent() .SetRadius( texture.Width / 2 ) .AddComponent( new Sprite( texture ) ); ``` -------------------------------- ### Nez Physics Class Methods Source: https://github.com/prime31/nez/blob/master/Nez.github.io/docs/features/Physics/NezPhysics.md Provides examples of commonly used methods from the Nez Physics class, which acts as a gateway to the physics system. These methods include linecasting for detecting colliders along a path, and overlap checks for finding colliders within specific shapes. ```csharp Physics.Linecast( startPos, endPos, layerMask ) Physics.OverlapRectangle( rect, layerMask ) Physics.OverlapCircle( center, radius, layerMask ) Physics.BoxcastBroadphase( collider ) ``` -------------------------------- ### Expose Methods for Inspector Callable Source: https://github.com/prime31/nez/blob/master/FAQs/RuntimeInspector.md This example demonstrates how to make methods callable from the Nez runtime inspector using the `InspectorCallable` attribute. Methods must accept zero or one parameter of type int, float, bool, or string. Methods with more than one parameter will not be callable. ```csharp [InspectorCallable] public void DoSomething() {} ``` ```csharp [InspectorCallable] public void DoSomethingWithParameter( bool isDone ) {} ``` ```csharp [InspectorCallable] public void ThisWontWorkBecauseItHasTwoParameters( bool isDone, int stuff ) {} ``` -------------------------------- ### State Machine with Object States (C#) Source: https://github.com/prime31/nez/blob/master/FAQs/AI.md Utilizes the 'states as objects' pattern for more complex AI systems. It uses separate classes for each state and supports a context object for relevant game information. The example shows instantiation, adding states, updating, and changing states. ```csharp // create a state machine that will work with an object of type SomeClass as the focus with an initial state of PatrollingState var machine = new SKStateMachine( someClass, new PatrollingState() ); // we can now add any additional states machine.AddState( new AttackState() ); machine.AddState( new ChaseState() ); // this method would typically be called in an update of an object machine.Update( Time.deltaTime ); // change states. the state machine will automatically create and cache an instance of the class (in this case ChasingState) machine.ChangeState(); ``` -------------------------------- ### Help Command in Nez Debug Console Source: https://github.com/prime31/nez/blob/master/Nez.github.io/docs/about/introduction.md Displays available commands in the in-game debug console. Use 'help COMMAND' for specific command details. ```bash help ``` -------------------------------- ### Custom Scene Transition with Effects in Nez Source: https://github.com/prime31/nez/blob/master/FAQs/lang.cn_wip/SceneTransitions.md Provides an example of a custom scene transition 'SuperTransition' that utilizes a custom shader effect ('TransitionEffect.mgfxo'). It shows how to inherit from SceneTransition, load and apply effects, manage transition progress, and handle rendering for both new scene loading and intra-scene transitions. ```csharp public class SuperTransition : SceneTransition { public float Duration = 1f; public EaseType EaseType = EaseType.QuartOut; Effect _effect; Rectangle _destinationRect; public SuperTransition( Func sceneLoadAction ) : base( sceneLoadAction, true ) { _destinationRect = previousSceneRender.Bounds; _effect = Core.content.loadEffect( "TransitionEffect.mgfxo" ); } public override IEnumerator OnBeginTransition() { yield return Core.StartCoroutine( LoadNextScene() ); yield return Core.StartCoroutine( TickEffectProgressProperty( _effect, duration, easeType ) ); TransitionComplete(); Core.Content.UnloadEffect( _effect ); } public override void Render( Batcher batcher ) { Core.graphicsDevice.SetRenderTarget( null ); batcher.Begin( BlendState.NonPremultiplied, Core.DefaultSamplerState, DepthStencilState.None, null, _effect ); batcher.Draw( previousSceneRender, _destinationRect, Color.White ); bbatcher.End(); } } ``` -------------------------------- ### Loading OGL/FXB Effects from Bytes Source: https://github.com/prime31/nez/blob/master/Nez.github.io/docs/features/ContentManagement.md Demonstrates loading OGL/FXB effects directly from a byte array, ensuring proper disposal. ```csharp content.LoadEffect( "effectName", effectCodeBytes ); ``` -------------------------------- ### Deploy Website to GitHub Pages (Yarn) Source: https://github.com/prime31/nez/blob/master/Nez.github.io/README.md Builds the website and deploys it to the 'gh-pages' branch, specifically configured for hosting on GitHub Pages. Requires setting the GIT_USER environment variable and optionally USE_SSH. ```console GIT_USER= USE_SSH=true yarn deploy ``` -------------------------------- ### Loading OGL/FXB Effects from File Source: https://github.com/prime31/nez/blob/master/Nez.github.io/docs/features/ContentManagement.md Illustrates loading OGL/FXB effects directly from a file path, with automatic disposal when the ContentManager is disposed. ```csharp content.LoadEffect("effectFileName"); ``` ```csharp content.LoadEffect( "effectFileName" ); ``` -------------------------------- ### Create Floor Entity Source: https://github.com/prime31/nez/blob/master/Nez.github.io/docs/features/Graphics/Stencil.md Creates a floor entity with a specified texture and render layer. This is a basic setup for scene geometry. ```csharp Entity floor = CreateEntity("floor"); floor.Position = center; var floorSprite = floor.AddComponent(new SpriteRenderer(floorTexture)); floorSprite.RenderLayer = 2; ```