### Install Prerequisites for Wine Setup
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_started/1_setting_up_your_os_for_development_ubuntu.md
Installs necessary packages like wget, curl, and p7zip-full, which are required for downloading and setting up Wine for effect compilation.
```bash
sudo apt install wget curl p7zip-full
```
--------------------------------
### Install MGFXC .NET Tool
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_started/tools/mgfxc.md
Installs the MGFXC tool globally using the .NET CLI. Ensure the .NET SDK is installed.
```bash
dotnet tool install -g dotnet-mgfxc
```
--------------------------------
### Setup WINE for Effect Compilation on Linux
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/tutorials/building_2d_games/02_getting_started/index.md
Installs necessary packages and sets up the WINE environment for effect compilation on Linux systems.
```shell
sudo apt-get update && sudo apt-get install -y curl p7zip-full wine64
wget -qO- https://monogame.net/downloads/net8_mgfxc_wine_setup.sh | bash
```
--------------------------------
### macOS Info.plist Example
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_started/packaging_games.md
An example of an Info.plist file for a macOS application bundle. This file contains essential metadata about your game.
```xml
CFBundleDevelopmentRegion
en
CFBundleExecutable
YourGame
CFBundleIconFile
YourGame
CFBundleIdentifier
com.your-domain.YourGame
CFBundleInfoDictionaryVersion
6.0
CFBundleName
YourGame
CFBundlePackageType
APPL
CFBundleShortVersionString
1.0
CFBundleSignature
FONV
CFBundleVersion
1
LSApplicationCategoryType
public.app-category.games
LSMinimumSystemVersion
10.15
NSHumanReadableCopyright
Copyright © 2022
NSPrincipalClass
NSApplication
LSRequiresNativeExecution
LSArchitecturePriority
arm64
```
--------------------------------
### Install .NET 9 SDK on Arch Linux
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_started/1_setting_up_your_os_for_development_arch.md
Installs the latest .NET 9 SDK using pacman. Ensure your system is up-to-date before installation.
```sh
sudo pacman -Syu
sudo pacman -S dotnet-sdk-9.0
```
--------------------------------
### LoadContent Method for Setup
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_to_know/howto/graphics/HowTo_Draw_Textured_Quad.md
Orchestrates the setup process by calling methods to set graphics states, configure the BasicEffect, define the quad's geometry, and generate or load the texture.
```csharp
protected override void LoadContent()
{
// Set render state
SetStates();
// Setup basic effect
SetUpBasicEffect();
// Create the quad to draw
SetupUserIndexedVertexRectangle(new Rectangle(10, 40, 450, 260));
// Generate (or load) the Texture
generatedTexture = GenerateTexture2D();
}
```
--------------------------------
### Full Microphone Recording Example
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_to_know/howto/audio/HowTo_Record_Microphone.md
A comprehensive C# example demonstrating microphone recording, playback, and management. Includes methods for checking microphone connection, selecting a microphone, and initializing the microphone, with continuous monitoring in the Update method.
```csharp
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace MonoGame.Samples.Microphone
{
public class MicrophoneSample : Game
{
private GraphicsDeviceManager _graphics;
private SpriteBatch _spriteBatch;
private Microphone _microphone;
private byte[] _buffer;
private bool _isRecording;
private List _recordedData;
private SpriteFont _font;
private string _statusMessage;
public MicrophoneSample()
{
_graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
IsMouseVisible = true;
}
protected override void Initialize()
{
// TODO: Add your initialization logic here
base.Initialize();
}
protected override void LoadContent()
{
_spriteBatch = new SpriteBatch(GraphicsDevice);
_font = Content.Load("Arial"); // Assuming you have an Arial font in Content.mgcb
InitializeMicrophone();
_recordedData = new List();
_statusMessage = "Press SPACE to start recording, P to stop.";
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
// Continuously monitor microphone connection
if (_microphone == null || !_microphone.IsInitialized)
{
InitializeMicrophone();
}
HandleInput();
base.Update(gameTime);
}
private void HandleInput()
{
var keyboardState = Keyboard.GetState();
if (keyboardState.IsKeyDown(Keys.Space) && _microphone != null && !_isRecording)
{
StartRecording();
}
if (keyboardState.IsKeyDown(Keys.P) && _isRecording)
{
StopRecording();
}
}
private void InitializeMicrophone()
{
if (Microphone.All.Length > 0)
{
_microphone = PickFirstConnectedMicrophone();
if (_microphone != null)
{
_microphone.BufferDuration = TimeSpan.FromMilliseconds(100);
_buffer = new byte[_microphone.GetSampleSizeInBytes(_microphone.BufferDuration)];
_microphone.BufferReady += Microphone_BufferReady;
_microphone.Start(); // Start immediately upon initialization
_isRecording = true;
_statusMessage = "Recording...";
}
else
{
_statusMessage = "No suitable microphone found.";
}
}
else
{
_statusMessage = "No microphone detected.";
}
}
private Microphone PickFirstConnectedMicrophone()
{
foreach (var mic in Microphone.All)
{
if (mic.IsInitialized)
{
return mic;
}
}
return null;
}
private void Microphone_BufferReady(object sender, EventArgs e)
{
if (_microphone == null || !_isRecording) return;
int dataRead = _microphone.GetData(_buffer);
if (dataRead > 0)
{
_recordedData.AddRange(_buffer.AsSpan(0, dataRead).ToArray());
}
}
private void StartRecording()
{
if (_microphone == null || _isRecording) return;
try
{
_recordedData.Clear(); // Clear previous recording
_microphone.Start();
_isRecording = true;
_statusMessage = "Recording...";
}
catch (Exception ex)
{
_statusMessage = "Error starting recording: " + ex.Message;
}
}
private void StopRecording()
{
if (_microphone == null || !_isRecording) return;
try
{
_microphone.Stop();
_isRecording = false;
_statusMessage = "Recording stopped. Press SPACE to record again.";
// Here you would typically process or play _recordedData
PlayRecordedData();
}
catch (Exception ex)
{
_statusMessage = "Error stopping recording: " + ex.Message;
}
}
private void PlayRecordedData()
{
if (_recordedData.Count == 0) return;
// Create a SoundEffect from the recorded data
// Note: This requires knowing the audio format (sample rate, channels, bit depth)
// For simplicity, assuming a common format. You might need to adjust this.
var sampleRate = _microphone.SampleRate;
var channels = _microphone.RecordingChannels;
var format = channels == 1 ? AudioChannels.Mono : AudioChannels.Stereo;
var buffer = _recordedData.ToArray();
// MonoGame's SoundEffect requires a specific format. If your microphone
// provides data in a different format, you'll need to convert it.
// This example assumes PCM 16-bit format which is common.
// If your mic data is not 16-bit PCM, you'll need to add conversion logic.
try
{
var soundEffect = new SoundEffect(buffer, sampleRate, format);
soundEffect.Play();
_statusMessage = "Playing back recorded audio...";
}
catch (Exception ex)
{
_statusMessage = "Error playing audio: " + ex.Message;
}
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
_spriteBatch.Begin();
_spriteBatch.DrawString(_font, _statusMessage, new Vector2(10, 10), Color.White);
_spriteBatch.End();
base.Draw(gameTime);
}
}
// Extension method to check if a Microphone is connected
public static class MicrophoneExtensions
{
public static bool IsConnected(this Microphone microphone)
{
// This is a simplified check. A more robust check might involve
// trying to access properties or methods that would throw if disconnected.
try
{
// Accessing a property like SampleRate can indicate if it's usable.
var _ = microphone.SampleRate;
return true;
}
catch (NoMicrophoneConnectedException)
{
return false;
}
catch (Exception)
{
// Handle other potential exceptions if necessary
return false;
}
}
}
}
```
--------------------------------
### MonoGame Game Constructor Setup
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/tutorials/building_2d_games/03_the_game1_file/index.md
The constructor handles basic setup like creating the GraphicsDeviceManager and setting initial properties.
```csharp
public Game1()
{
_graphics = new GraphicsDeviceManager(this);
}
```
--------------------------------
### Install Android, iOS, and MAUI Workloads
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_started/1_setting_up_your_os_for_development_macos.md
Run this command in the terminal to install the .NET workloads for Android, iOS, and MAUI development. This is required for mobile development.
```cli
dotnet workload install android ios maui
```
--------------------------------
### Initialize Method for Game Setup
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_started/3_understanding_the_code.md
Called after the constructor and before the game loop for initializing services and non-graphic content.
```csharp
protected override void Initialize()
{
// TODO: Add your initialization logic here
base.Initialize();
}
```
--------------------------------
### Example MGCB Response File
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_started/tools/mgcb.md
Defines build options and assets for the MGCB tool. Each switch is on a new line, and comments start with '#'.
```sh
# Directories
/outputDir:bin/foo
/intermediateDir:obj/foo
/rebuild
# Build a texture
/importer:TextureImporter
/processor:TextureProcessor
/processorParam:ColorKeyEnabled=false
/build:Textures\wood.png
/build:Textures\metal.png
/build:Textures\plastic.png
```
--------------------------------
### Handle Start Button Click
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/tutorials/building_2d_games/20_implementing_ui_with_gum/index.md
Plays a UI sound effect and changes the scene to the game scene when the "Start" button is clicked.
```csharp
void HandleStartClicked(object sender, EventArgs e)
{
// Play UI sound effect
// AudioManager.PlaySound("ui_click");
// Change scene to the game scene
ScreenManager.ChangeScreen("GameScene");
}
```
--------------------------------
### Install .NET SDK on Linux
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/tutorials/building_2d_games/02_getting_started/index.md
Installs the .NET SDK version 8.0 on Linux systems using apt-get. Ensure your system's package list is updated before running.
```bash
sudo apt-get update && sudo apt-get install -y dotnet-sdk-8.0
```
--------------------------------
### Install MGCB .NET Tool
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_started/tools/mgcb.md
Installs the MonoGame Content Builder as a global .NET tool. Ensure the .NET SDK is installed before running this command.
```sh
dotnet tool install -g dotnet-mgcb
```
--------------------------------
### Start Microphone Recording
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_to_know/howto/audio/HowTo_Record_Microphone.md
Begin recording audio from the microphone. This method starts the microphone if it exists and is not already running. Handles potential disconnection exceptions.
```csharp
private void StartRecording()
{
// Can't start a microphone that doesn't exist.
if (activeMicrophone == null) { return; }
try
{
activeMicrophone.Start();
}
catch (NoMicrophoneConnectedException)
{
// Microphone was disconnected - let the user know.
}
```
--------------------------------
### MonoGame Installation Instructions Template
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/tutorials/building_2d_games/26_publish_to_itch/index.md
Provides a template for creating platform-specific installation instructions for a MonoGame project distributed as an archive. Includes steps for extraction and execution on Windows, Linux, and macOS, with notes on setting file permissions for Linux and macOS.
```text
Once the download has completed:
For Windows:
1. Extract the contents of the ZIP archive.
2. Run the "[YourGameName].exe" executable from the extracted folder.
For Linux:
1. Extract the contents of the tar.gz archive.
2. Run the "[YourGameName]" executable from the extracted folder.
3. If the game does not open or states it is not executable, you may need to change the file permissions. To do this:
1. Open a terminal in the extracted directory.
2. Make the game executable with the command: chmod +x ./[YourGameName]
For macOS:
1. Extract the contents of the tar.gz archive.
2. Run the [YourGameName].app executable from the extracted folder.
3. If the game does not open or states it is not an executable, you may need to change the file permissions. To do this:
1. Open a terminal in the extracted directory.
2. Make the game executable with the command: chmod +x ./[YourGameName].app/Contents/MacOS/[YourGameName]
```
--------------------------------
### Game Constructor Initialization
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_started/3_understanding_the_code.md
Initializes starting variables: GraphicsDeviceManager, content root directory, and mouse visibility.
```csharp
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
IsMouseVisible = true;
}
```
--------------------------------
### Circle Equality Example
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/tutorials/building_2d_games/12_collision_detection/index.md
Example demonstrating the use of operator overloads for comparing circles.
```csharp
Circle c1 = new Circle(10, 10, 5);
Circle c2 = new Circle(10, 10, 5);
if (c1 == c2)
{
// c1 and c2 are equal
}
```
--------------------------------
### Install Homebrew and Wine
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_started/1_setting_up_your_os_for_development_macos.md
Installs necessary prerequisites like wget, p7zip, curl, and the stable Wine version using Homebrew. It also removes the quarantine attribute from the Wine application, which is required for it to run on macOS.
```sh
brew install wget p7zip curl && brew install --cask wine-stable && xattr -dr com.apple.quarantine "/Applications/Wine Stable.app"
```
--------------------------------
### Install iOS Workload
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_started/1_setting_up_your_os_for_development_macos.md
Run this command in the terminal to install the .NET workload for iOS development. This is required for mobile development.
```cli
dotnet workload install ios
```
--------------------------------
### Install Android Workload
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_started/1_setting_up_your_os_for_development_macos.md
Run this command in the terminal to install the .NET workload for Android development. This is required for mobile development.
```cli
dotnet workload install android
```
--------------------------------
### Install Wine and Dependencies on Arch Linux
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_started/1_setting_up_your_os_for_development_arch.md
Installs Wine and essential dependencies for effect compilation. This includes wget, curl, and 7zip.
```sh
sudo pacman -S wget curl 7zip wine
```
--------------------------------
### Install .NET 9 SDK on Ubuntu
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_started/1_setting_up_your_os_for_development_ubuntu.md
Installs the .NET 9 SDK required for MonoGame development. Ensure your system's package list is updated before running.
```bash
sudo apt-get update && sudo apt-get install -y dotnet-sdk-9.0
```
--------------------------------
### Install Platform-Specific .NET Workloads
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_started/content_pipeline/automating_content_builder.md
Installs necessary .NET workloads for specific platforms if a workload is defined in the build matrix. This is conditional and only runs when `matrix.workload` is not empty.
```yaml
- name: Install workload
if: ${{ matrix.workload != '' }}
run: dotnet workload install ${{ matrix.workload }}
```
--------------------------------
### Search for .NET Workloads
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_started/1_setting_up_your_os_for_development_windows.md
Use this command to discover available .NET workloads that can be installed. This is useful for identifying additional platform support.
```cli
dotnet workload search
```
--------------------------------
### Load Texture and Setup Cube
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_to_know/howto/graphics/HowTo_UseACustomVertex.md
Load the texture to be used and call the method to set up the vertex buffer for the cube in the LoadContent method.
```csharp
logoTexture = Content.Load("logo");
SetupDrawingCube();
```
--------------------------------
### Initialize Single PointLight and ShadowCaster
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/tutorials/advanced/2d_shaders/09_shadows_effect/index.md
Temporarily replace InitializeLights() in GameScene for basic setup with one PointLight and one ShadowCaster.
```csharp
private void InitializeLights() {
// For now, to keep things simple, temporarily replace the InitializeLights() function
// in the GameScene to have a single PointLight and a single ShadowCaster:
var pointLight = new PointLight(new Vector2(GraphicsDevice.Viewport.Width / 2, GraphicsDevice.Viewport.Height / 2), 200f, Color.White);
_pointLights.Add(pointLight);
var shadowCaster = new ShadowCaster(new Vector2(100, 100), new Vector2(200, 200));
_shadowCasters.Add(shadowCaster);
}
```
--------------------------------
### Example Error Message MGFX0001 (Linux)
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/errors/mgfx0001/index.md
This is an example of the MGFX0001 error message displayed when Wine is not properly installed or configured on Linux.
```text
Error: MGFXC0001: MGFXC effect compiler requires a valid Wine installation to be able to compile shaders. Please visit https://docs.monogame.net/errors/mgfx0001?tab=linux for more details.
```
--------------------------------
### Example Error Message MGFX0001 (macOS)
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/errors/mgfx0001/index.md
This is an example of the MGFX0001 error message displayed when Wine is not properly installed or configured on macOS.
```text
Error: MGFXC0001: MGFXC effect compiler requires a valid Wine installation to be able to compile shaders. Please visit https://docs.monogame.net/errors/mgfx0001?tab=macos for more details.
```
--------------------------------
### Create a Simple ImGui Window
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/tutorials/advanced/2d_shaders/04_debug_ui/index.md
Create a basic ImGui window with "Hello World" text by using ImGui.Begin() and ImGui.End() within the UI layout.
```csharp
ImGui.Begin("Debug");
ImGui.Text("Hello World");
ImGui.End();
```
--------------------------------
### Install Preview Templates
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_to_know/howto/HowTo_Install_Preview_Release.md
Install the latest MonoGame C# project templates, including any preview versions, to generate new projects with the latest setup. Replace the version number with the specific preview version you wish to install.
```dotnetcli
dotnet new install MonoGame.Templates.CSharp::3.8.4-preview.1
```
--------------------------------
### Example Command Line Arguments for Content Builder
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_started/content_pipeline/content_builder_project.md
Demonstrates how to pass arguments to the content builder executable. These arguments correspond to the properties configurable in ContentBuilderParams.
```bash
mybuilder.exe --src "MyAssets" --output "bin/Content" --platform DesktopGL --compress
```
--------------------------------
### Check Wine Version
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_started/1_setting_up_your_os_for_development_arch.md
Verify your installed Wine version to ensure it meets the MonoGame setup script requirements (8.0 or later).
```shell
wine --version
```
--------------------------------
### Read Multi-Touch Data
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_to_know/howto/input/HowTo_UseMultiTouchInput.md
Get the current touch state using TouchPanel.GetState. Iterate through the TouchCollection to process each TouchLocation. This example adds sparkles at touch locations that are pressed or have moved.
```csharp
// Process touch events
TouchCollection touchCollection = TouchPanel.GetState();
foreach (TouchLocation tl in touchCollection)
{
if ((tl.State == TouchLocationState.Pressed)
|| (tl.State == TouchLocationState.Moved))
{
// add sparkles based on the touch location
sparkles.Add(new Sparkle(tl.Position.X,
tl.Position.Y, ttms));
}
}
```
--------------------------------
### GameScene Initialize Method - C#
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/tutorials/building_2d_games/23_completing_the_game/index.md
Sets up the initial state of the game scene, including disabling exit on escape, calculating playable area, subscribing to slime collision events, initializing UI, and starting a new game.
```csharp
public override void Initialize() {
base.Initialize();
// Disable default exit on escape behavior to use it for pausing
IsExitOnEscape = false;
// Calculate the playable area within the tilemap walls
_roomBounds = _tilemap.GetPlayableArea();
// Subscribe to the slime's body collision event to trigger game over
_slime.BodyCollided += (sender, args) => {
if (_state == GameState.Playing) {
_state = GameState.GameOver;
_ui.ShowGameOverPanel(true);
}
};
// Initialize the UI components
_ui = new GameSceneUI(Content);
_ui.Initialize();
// Set up a new game
StartNewGame();
}
```
--------------------------------
### Start the Content Watcher Manually
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/tutorials/advanced/2d_shaders/02_hot_reload/index.md
This shell command starts the content watcher. It must be run before starting the game for hot reloading to function.
```sh
dotnet run --project ../../Tools/ContentWatcher/ContentWatcher.csproj
```
--------------------------------
### Initialize Viewports and Projection Matrices
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_to_know/howto/graphics/HowTo_UseViewportForSplitscreenGaming.md
Set up two Viewport objects for a vertical split and create corresponding projection matrices. The left viewport takes half the screen width, and the right viewport starts at the midpoint.
```csharp
Viewport defaultViewport;
Viewport leftViewport;
Viewport rightViewport;
Matrix projectionMatrix;
Matrix halfprojectionMatrix;
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
defaultViewport = GraphicsDevice.Viewport;
leftViewport = defaultViewport;
rightViewport = defaultViewport;
leftViewport.Width = leftViewport.Width / 2;
rightViewport.Width = rightViewport.Width / 2;
rightViewport.X = leftViewport.Width;
projectionMatrix = Matrix.CreatePerspectiveFieldOfView(
MathHelper.PiOver4, 4.0f / 3.0f, 1.0f, 10000f);
halfprojectionMatrix = Matrix.CreatePerspectiveFieldOfView(
MathHelper.PiOver4, 2.0f / 3.0f, 1.0f, 10000f);
}
```
--------------------------------
### Complete Game1.cs Example
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/tutorials/building_2d_games/05_content_pipeline/index.md
This is the complete Game1.cs file demonstrating the integration of loading and drawing a texture. It includes the necessary field declaration, LoadContent, and Draw method implementations.
```csharp
// The MonoGame logo texture
private Texture2D _logo;
protected override void LoadContent()
{
_logo = Content.Load("images/logo");
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// Begin the sprite batch to prepare for rendering.
SpriteBatch.Begin();
// Draw the logo texture
SpriteBatch.Draw(_logo, Vector2.Zero, Color.White);
// Always end the sprite batch when finished.
SpriteBatch.End();
base.Draw(gameTime);
}
```
--------------------------------
### Install yay AUR Helper on Arch Linux
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_started/2_choosing_your_ide_vscode.md
Installs the 'yay' AUR helper, which is required to install packages from the Arch User Repository, such as the official Visual Studio Code.
```sh
sudo pacman -S git base-devel
git clone https://aur.archlinux.org/yay.git
cd yay
makepkg -si
```
--------------------------------
### Initialize Matrices for BasicEffect
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_to_know/howto/graphics/HowTo_Create_a_BasicEffect.md
Set up the world, view, and projection matrices in the Initialize method. The view matrix uses CreateLookAt, and the projection matrix uses CreatePerspectiveFieldOfView.
```csharp
protected override void Initialize()
{
// Setup the matrices to look forward
worldMatrix = Matrix.Identity;
viewMatrix = Matrix.CreateLookAt(new Vector3(0, 0, 50), Vector3.Zero, Vector3.Up);
projectionMatrix = Matrix.CreatePerspectiveFieldOfView(
MathHelper.PiOver4,
GraphicsDevice.Viewport.AspectRatio,
1.0f, 300.0f);
base.Initialize();
}
```
--------------------------------
### Initialize Game in Full-Screen Mode
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_to_know/howto/graphics/HowTo_FullScreen.md
Set PreferredBackBufferWidth, PreferredBackBufferHeight, and IsFullScreen to true in the Game constructor to initialize the game in full-screen mode with a specific resolution.
```csharp
public Game1()
{
_graphics = new GraphicsDeviceManager(this);
// Setup up the default resolution for the project
_graphics.PreferredBackBufferWidth = 800;
_graphics.PreferredBackBufferHeight = 480;
// Runs the game in "full Screen" mode using the set resolution
_graphics.IsFullScreen = true;
Content.RootDirectory = "Content";
IsMouseVisible = true;
}
```
--------------------------------
### Docking a Panel to Fill
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/tutorials/building_2d_games/20_implementing_ui_with_gum/index.md
This snippet demonstrates how to create a panel and dock it to fill the entire root space. It's useful for establishing a base layout that occupies the whole screen.
```cs
Panel mainMenuPanel = new Panel();
mainMenuPanel.AddToRoot();
// Docking the panel to fill the entire root space
mainMenuPanel.Dock(Gum.Wireframe.Dock.Fill);
```
--------------------------------
### Generated XML Output Example
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_to_know/howto/content_pipeline/HowTo_GenerateCustomXML.md
This is an example of the XML structure generated by the content pipeline. Ensure your custom data types are correctly serialized.
```xml
23
Hello World
```
--------------------------------
### Basic ContentCollection Setup
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_started/content_pipeline/content_builder_project.md
Defines rules for handling content files, including effects, spritefonts, and PNG images from specific folders. Use this to organize and selectively import assets.
```csharp
public override IContentCollection GetContentCollection()
{
var contentCollection = new ContentCollection();
// Only effect files from the Effects folder
contentCollection.Include("Effects/*.fx");
// Only spritefonts from the Fonts folder (not ttf)
contentCollection.Include("Fonts/*.spritefont");
// Only import PNG files from the Textures Folder
contentCollection.Include("Textures/*.png");
contentCollection.Include("splash-screen.png");
return contentCollection;
}
```
--------------------------------
### Create Info.plist File
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/tutorials/building_2d_games/25_packaging_game/index.md
Use the `touch` command to create an empty `Info.plist` file within the `Contents/` directory of your application bundle. This file will be populated with essential application metadata.
```bash
touch bin/Release/DungeonSlime.app/Contents/Info.plist
```
--------------------------------
### Document Frontmatter Example
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/README.md
This is an example of document frontmatter used in Markdown files. It controls the page title, description, and MS license statement inclusion.
```yaml
---
title: How to create a Render Target
description: Demonstrates how to create a render target using a RenderTarget2D.
requireMSLicense: true
---
```
--------------------------------
### Serve MonoGame Documentation (macOS/Linux)
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/README.md
Execute this Bash script on macOS or Linux to build and serve the MonoGame documentation locally. It handles submodule initialization and API documentation assembly.
```bash
./serve.sh
```
--------------------------------
### Initialize BasicEffect with Transformations and Lighting
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_to_know/howto/graphics/HowTo_Create_a_BasicEffect.md
In LoadContent, create a BasicEffect instance and set its World, View, and Projection matrices. Configure lighting and color properties, and enable vertex color rendering.
```csharp
protected override void LoadContent()
{
basicEffect = new BasicEffect(_graphics.GraphicsDevice);
basicEffect.World = worldMatrix;
basicEffect.View = viewMatrix;
basicEffect.Projection = projectionMatrix;
// primitive color
basicEffect.AmbientLightColor = new Vector3(0.1f, 0.1f, 0.1f);
basicEffect.DiffuseColor = new Vector3(1.0f, 1.0f, 1.0f);
basicEffect.SpecularColor = new Vector3(0.25f, 0.25f, 0.25f);
basicEffect.SpecularPower = 5.0f;
basicEffect.Alpha = 1.0f;
// The following MUST be enabled if you want to color your vertices
basicEffect.VertexColorEnabled = true;
// Use the built in 3 lighting mode provided with BasicEffect
basicEffect.EnableDefaultLighting();
}
```
--------------------------------
### Install MonoGame Mobile Workloads
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/tutorials/building_2d_games/02_getting_started/index.md
Installs the necessary .NET workloads for developing MonoGame applications targeting iOS and Android. Run these commands in your terminal or command prompt.
```bash
dotnet workload install ios
dotnet workload install android
```
--------------------------------
### Serve MonoGame Documentation (Windows)
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/README.md
Execute this PowerShell script on Windows to build and serve the MonoGame documentation locally. It handles submodule initialization and API documentation assembly.
```powershell
.\serve.ps1
```
--------------------------------
### Initialize Camera and Projection Matrices
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_to_know/howto/graphics/HowTo_Draw_3D_Primitives.md
Sets up world, view, and projection matrices for rendering. Uses an orthographic projection suitable for 2D-like rendering or specific 3D views. The view matrix positions the camera, and the projection matrix defines the viewing frustum.
```csharp
// Matrix to translate the drawn primitives to the center of the screen.
private Matrix translationMatrix;
// Number of vertex points to draw the primitive with.
private int points = 8;
// The length of the primitive lines to draw.
private int lineLength = 100;
protected override void Initialize()
{
worldMatrix = Matrix.Identity;
viewMatrix = Matrix.CreateLookAt(
new Vector3(0.0f, 0.0f, 1.0f),
Vector3.Zero,
Vector3.Up
);
projectionMatrix = Matrix.CreateOrthographicOffCenter(
0,
(float)GraphicsDevice.Viewport.Width,
(float)GraphicsDevice.Viewport.Height,
0,
1.0f, 1000.0f);
// Calculate the center of the visible screen using the ViewPort.
Vector2 screenCenter = new Vector2(GraphicsDevice.Viewport.Width / 2, GraphicsDevice.Viewport.Height / 2);
// Calculate the center of the primitives to be drawn.
var primitiveCenter = new Vector2((points / 2 - 1) * lineLength / 2, lineLength / 2);
// Create a translation matrix to position the drawn primitives in the center of the screen and the center of the primitives.
translationMatrix = Matrix.CreateTranslation(screenCenter.X - primitiveCenter.X, screenCenter.Y - primitiveCenter.Y, 0);
base.Initialize();
}
```
--------------------------------
### Install Code OSS on Arch Linux
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_started/2_choosing_your_ide_vscode.md
Installs the open-source version of VS Code using pacman. Note that this version does not support the proprietary Microsoft C# Dev Kit extension.
```sh
sudo pacman -S code
```
--------------------------------
### Build macOS Intel (x64) Application Bundle
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/tutorials/building_2d_games/25_packaging_game/index.md
Use this .NET CLI command to create a self-contained application bundle for Intel-based macOS systems. It targets the Release configuration and disables ReadyToRun and Tiered Compilation.
```bash
dotnet publish -c Release -r osx-x64 -p:PublishReadyToRun=false -p:TieredCompilation=false --self-contained
```
--------------------------------
### Trigger Collision Response Example
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/tutorials/building_2d_games/12_collision_detection/index.md
Implement a trigger collision response to activate an event when a game object overlaps with a trigger zone. This example checks for overlap and triggers an event if detected.
```csharp
if (player.BoundingBox.Intersects(triggerZone.BoundingBox))
{
// Trigger event
triggerZone.ActivateEvent();
}
```
--------------------------------
### Create Universal Binary with lipo
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/tutorials/building_2d_games/25_packaging_game/index.md
Utilize the `lipo` command to create a universal binary by combining Intel (x64) and Apple Silicon (arm64) executables. This ensures your application runs natively on both architectures.
```bash
lipo -create bin/Release/net8.0/osx-arm64/publish/DungeonSlime bin/Release/net8.0/osx-x64/publish/DungeonSlime -output bin/Release/DungeonSlime.app/Contents/MacOS/DungeonSlime
```
--------------------------------
### Blocking Collision Response Example
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/tutorials/building_2d_games/12_collision_detection/index.md
Implement a blocking collision response to prevent objects from overlapping. This example checks for overlap at a new position and reverts to the previous position if an overlap occurs.
```csharp
if (newPosition.Intersects(otherObject.BoundingBox))
{
// Overlap detected, revert to previous position
position = oldPosition;
}
else
{
// No overlap, update position
position = newPosition;
}
```
--------------------------------
### Install MonoGame C# Templates
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_started/2_choosing_your_ide_vscode.md
Installs the official MonoGame C# project templates using the .NET CLI. This command enables the creation of new MonoGame projects within Visual Studio Code.
```sh
dotnet new install MonoGame.Templates.CSharp
```
--------------------------------
### Install MAUI Workload
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_started/1_setting_up_your_os_for_development_macos.md
Run this command in the terminal to install the .NET workload for MAUI development. This is required for mobile development, even though MonoGame does not use MAUI directly, as it contains necessary debugging tools.
```cli
dotnet workload install maui
```
--------------------------------
### GamePadInfo Constructor
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/tutorials/building_2d_games/11_input_management/index.md
Initialize the GamePadInfo with a PlayerIndex and set initial gamepad states.
```csharp
public GamePadInfo(PlayerIndex index)
{
Index = index;
PreviousState = GamePad.GetState(index);
CurrentState = PreviousState;
IsConnected = CurrentState.IsConnected;
}
```
--------------------------------
### Initialize GraphicsDeviceManager
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_to_know/howto/graphics/HowTo_Scale_Sprites_Matrix.md
Set the preferred back buffer height and width in the Game constructor to define the default screen size.
```csharp
public Game1()
{
_graphics = new GraphicsDeviceManager(this)
{
PreferredBackBufferHeight = 600,
PreferredBackBufferWidth = 800
};
Content.RootDirectory = "Content";
IsMouseVisible = true;
}
```
--------------------------------
### Update Content Manager Tools
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_to_know/howto/HowTo_Install_Preview_Release.md
Install or update the MGCB tools to match the preview version of MonoGame. This ensures compatibility between your project and the Content Pipeline Editor. Replace the version number with the specific preview version you wish to install.
```dotnetcli
dotnet tool install dotnet-mgcb --version 3.8.4-preview.1
dotnet tool install dotnet-mgcb-editor --version 3.8.4-preview.1
dotnet tool install dotnet-mgcb-editor-linux --version 3.8.4-preview.1
dotnet tool install dotnet-mgcb-editor-windows --version 3.8.4-preview.1
dotnet tool install dotnet-mgcb-editor-mac --version 3.8.4-preview.1
```
--------------------------------
### Install Visual Studio Code (Official) on Arch Linux
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_started/2_choosing_your_ide_vscode.md
Installs the official Microsoft version of Visual Studio Code from the AUR using the 'yay' helper. This version supports proprietary extensions like the C# Dev Kit.
```sh
yay -S visual-studio-code-bin
```
--------------------------------
### Build macOS Apple Silicon (arm64) Application Bundle
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/tutorials/building_2d_games/25_packaging_game/index.md
This .NET CLI command is used to create a self-contained application bundle specifically for Apple Silicon (arm64) Macs. It is similar to the Intel build but targets the arm64 runtime.
```bash
dotnet publish -c Release -r osx-arm64 -p:PublishReadyToRun=false -p:TieredCompilation=false --self-contained
```
--------------------------------
### Launch RenderDoc with Executable Path
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/tutorials/advanced/2d_shaders/04_debug_ui/index.md
Specify the path to the built executable in RenderDoc's 'Launch Application' tab to begin capturing graphics API calls.
```sh
C:\\Users\\YourUsername\\Projects\\DungeonSlime\\bin\\Windows\\net9.0\\DungeonSlime.exe
```
--------------------------------
### Pass LightBuffer to Material
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/tutorials/advanced/2d_shaders/08_light_effect/index.md
Passes the LightBuffer to the material in the DrawComposite function before the sprite batch starts.
```csharp
deferredCompositeMaterial.Parameters["LightBuffer"].SetValue(lightBuffer);
```
--------------------------------
### Load SoundEffect and Create Instance
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_to_know/howto/audio/HowTo_ChangePitchAndVolume.md
Load a sound effect from a stream and create an instance of it in the LoadContent method. Ensure the audio file is set to 'COPY' in the MGCB tool.
```csharp
using Stream soundfile = TitleContainer.OpenStream(@"Content\tx0_fire1.wav");
soundEffect = SoundEffect.FromStream(soundfile);
soundEffectInstance = soundEffect.CreateInstance();
```
--------------------------------
### GamePadInfo Vibration Methods
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/tutorials/building_2d_games/11_input_management/index.md
Methods to control gamepad vibration, including starting and stopping effects.
```csharp
public void SetVibration(float leftVibration, float rightVibration, float duration)
{
VibrationLeft = leftVibration;
VibrationRight = rightVibration;
VibrationTimeLeft = duration;
VibrationTimeRight = duration;
GamePad.SetVibration(Index, VibrationLeft, VibrationRight);
}
public void StopVibration()
{
VibrationLeft = 0f;
VibrationRight = 0f;
VibrationTimeLeft = 0f;
VibrationTimeRight = 0f;
GamePad.SetVibration(Index, VibrationLeft, VibrationRight);
}
```
--------------------------------
### Create and Populate Processor Parameters
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_to_know/whatis/content_pipeline/CP_CustomParamProcs.md
Create an OpaqueDataDictionary and add parameters to it. These parameters will be passed to a chained processor.
```csharp
//create a dictionary to hold the processor parameter
OpaqueDataDictionary parameters = new OpaqueDataDictionary();
//add several parameters to the dictionary
parameters.Add( "ColorKeyColor", Color.Magenta );
parameters.Add( "ColorKeyEnabled", true );
parameters.Add( "ResizeToPowerOfTwo", true );
```
--------------------------------
### Get Default Microphone
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_to_know/howto/audio/HowTo_Record_Microphone.md
Obtain the default microphone device. Handle the case where no microphone is attached.
```csharp
Microphone activeMicrophone;
activeMicrophone = Microphone.Default;
if (activeMicrophone != null)
{
}
else
{
// No microphone is attached to the device
}
```
--------------------------------
### Create and Anchor a Button
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/tutorials/building_2d_games/20_implementing_ui_with_gum/index.md
Demonstrates how to create a Button and anchor it to the bottom-left of the screen. Position it with X and Y offsets.
```cs
// Creating a button that is anchored to the bottom left.
Button startButton = new Button;
startButton.Anchor(Gum.Wireframe.Anchor.BottomLeft);
// Set the X and Y position so it is 20px from the left edge
// and 20px from the bottom edge.
startButton.X = 20;
startButton.Y = -20;
```
--------------------------------
### Basic Build-Content Action Usage
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/getting_started/content_pipeline/automating_content_builder.md
Use this YAML snippet in your GitHub Actions workflow to process game content. It checks out code, sets up the .NET SDK, and runs the build-content action with specified paths and platform.
```yaml
name: Build Game with Content
on:
workflow_dispatch:
jobs:
build:
runs-on: windows-latest
steps:
- uses: actions/checkout@v5
- name: Setup .NET
uses: actions/setup-dotnet@v5
with:
dotnet-version: '9.0.x'
- name: Process content
uses: MonoGame/monogame-actions/build-content@v1
with:
content-builder-path: './Content/Builder'
assets-path: './Content/Assets'
monogame-platform: 'DesktopGL'
output-folder: './MyGame/bin/Release/Content'
configuration: Release
- name: Build game
run: dotnet build -c Release MyGame/MyGame.csproj -r win-x64
```
--------------------------------
### Update CheckGamePadInput for Pausing
Source: https://github.com/monogame/docs.monogame.github.io/blob/main/articles/tutorials/building_2d_games/20_implementing_ui_with_gum/index.md
Update the gamepad input handling to pause the game when the start button is pressed.
```csharp
if (currentGameState.Buttons.Start == ButtonState.Pressed) {
if (!isPaused) {
ShowPauseMenu();
} else {
HidePauseMenu();
}
}
```