This commit is contained in:
Lucas Girouard-Stranks
2020-11-30 17:41:52 -05:00
parent 3678ef907d
commit 17d8a5e265
46 changed files with 0 additions and 1663 deletions
-1
View File
@@ -1 +0,0 @@
docs.monogameextended.net
-11
View File
@@ -1,11 +0,0 @@
# Community and Support
MonoGame.Extended has a growing community of users from all around the globe. We've got lots of ways you can ask questions and get help about the library.
- Of course, there's [this documentation](http://craftworkgames.github.io/MonoGame.Extended/). By contributing to it you're making it better for everyone.
- We've got our own section on the [MonoGame Community Forums](http://community.monogame.net/c/extended)
- We've even got a [tag on stackoverflow](http://gamedev.stackexchange.com/questions/tagged/monogame-extended) ;)
- Development is usually discussed in [github issues](https://github.com/craftworkgames/MonoGame.Extended/issues)
- We've got a live chatroom on [gitter](https://gitter.im/craftworkgames/MonoGame.Extended)
Note: When you ask a question, please consider how permanent the answer should be. If it's something that might benefit others choose the docs, forum or stack overflow over live chat.
-35
View File
@@ -1,35 +0,0 @@
# Building the MonoGame PCL
This guide is about building the MonoGame [Portable Class Library](https://msdn.microsoft.com/en-us/library/gg597391) (PCL) found in the [Dependencies folder](https://github.com/craftworkgames/MonoGame.Extended/tree/develop/Dependencies) of the project.
**Note**: This is NOT a guide about building MonoGame.Extended from source. You won't need this guide unless you're trying to update the dependencies.
One of the challenges with using MonoGame is getting your project set up so that you can separate platform-specific and platform-independent code. One way, which we are using with MonoGame.Extended is to compile against a PCL ([Portable Class Library](https://msdn.microsoft.com/en-us/library/gg597391)). Instead of creating a platform specific binary of MonoGame.Extended for each platform, a cross-platform library is used and the platform specific code is substituted in later. A PCL is created through a certain set of tools such as [Visual Studio](https://www.visualstudio.com) on Windows, [Xamarin Studio](https://xamarin.com/studio) on Windows and Mac, or [MonoDevelop](http://www.monodevelop.com) on Windows, Mac and Linux. Since PCLs are designed to be cross-platform they can be created with one toolchain and used through a different toolchain.
With MonoGame, making a PCL isn't so easy since a large amount of platform-specific code is mixed in with other code, so you can't (at the moment) make a PCL of MonoGame directly. There are a few other issues as well, but I won't go into those. The solution to this is to use a tool to scrape all of the platform-specific implementation details from a specific MonoGame platform library. It doesn't really matter if it's the WindowsGL platform version that is used for this, but it's recommended.
## Install Tools
The first step in generating the PCL is to install the required tools. If you have Visual Studio, Xamarin Studio, you already have the tools. For Linux, you have to install the tools from Mono. To install Mono on a specific Linux distribution follow [their directions on the Mono website](http://www.mono-project.com/docs/getting-started/install/linux/). The important packages to install are `mono-complete`, which installs the complete mono runtime and development tools (including the tools in `mono-devel` if I remember correctly), and also the `referenceassemblies-pcl` package, which installs tools and references required for PCL generation and usage.
## Get MonoGame Source
Next, clone down the copy of [MonoGame from GitHub](https://github.com/mono/MonoGame) that you want to generate a PCL for. Remember that a PCL that is generated will probably only be usable with binaries made from that exact same commit.
## Build MonoGame
After you have cloned the repository, follow the MonoGame build instructions and use Protobuild to generate the set of `.sln` files and `.csproj` files for your platform. Open up the solution, then compile it.
## "Piranha" Binary into PCL
Finally, you need a copy of @Ark-kun's [Piranha tool, which "chews" binaries to make them into PCLs](https://github.com/Ark-kun/Piranha). Download a copy of his repository from GitHub, then build it. Navigate to where Piranha is built and open up command prompt if you are on Windows (PROTIP: shift-right-click on the Explorer background and select "Open command window here"), or Terminal if you are on Mac or Linux (MAC USERS PROTIP: type "cd" into terminal then drag and drop the folder into the terminal window and hit return). Enter the following command where `PATH_TO_MONOGAME_FRAMEWORK_DLL` is the path to the target `MonoGame.Framework.dll`:
Windows Users:
`Piranha.exe make-portable-skeleton -p ".NETPortable,Version=v4.5,Profile=Profile111" -i "PATH_TO_MONOGAME_FRAMEWORK_DLL" -o MonoGame.Framework.dll`
Mac and Linux Users:
`mono Piranha.exe make-portable-skeleton -p ".NETPortable,Version=v4.5,Profile=Profile111" -i "PATH_TO_MONOGAME_FRAMEWORK_DLL" -o MonoGame.Framework.dll`
Note that the .NET framework portable profile might need to be changed to match your project.
Piranha should of completed successfully and generated a portable `MonoGame.Framework.dll`.
-19
View File
@@ -1,19 +0,0 @@
# Building From Source
Ideally building from source should be as straightforward as possible. Everything should build right out of the repository. However, there are some external factors that can sometimes make things more difficult.
MonoGame.Extended uses a few newish technologies:
- [MonoGame 3.6](http://www.monogame.net/downloads/).
- C# 6.0 and Portable Class Library support in your IDE.
- .NET Framework 4.5 or equivalent (Mono).
- An up to date NuGet package manager
If you're building on Windows I highly recommend using [Visual Studio 2015](https://www.visualstudio.com/en-us/downloads/download-visual-studio-vs.aspx) because it supports all of the above out of the box.
There's not much more to it than that. Download the source using you're favorite git client and build.
git clone https://github.com/craftworkgames/MonoGame.Extended.git
On the first build the solution will download several NuGet packages.
Once the code builds, you can play with the demos in the `Demos` folder.
-46
View File
@@ -1,46 +0,0 @@
# Documentation
## We need your help writing better documentation
- Good documentation is what separates good open source projects from great ones.
- Documentation is a community effort.
- Even a little bit of documentation is better than none.
- A rough draft is better than none.
- If we all wrote a little documentation, it adds up to a lot.
## How to contribute to the documentation
The docs are located in the source [Docs/](https://github.com/craftworkgames/MonoGame.Extended/tree/develop/Docs) folder. They are built with [MkDocs](http://www.mkdocs.org/#installation).
- If you spot an error in the documentation, fix it. This is the simplest way to contribute.
- If you notice some missing or out of date information, add it. This is the next simplest way to contribute.
- If there's something completely missing, write a stub page. It's a start.
- If you want to go a step further, write a tutorial or a whole new page.
- If you have any trouble editing the docs, please [tell somebody](#community-and-support).
- You can edit the page directly on Github, it's Markdown, so you don't necessesarily need to install MkDocs to contribute.
## Getting started with MKDocs
Running your own dev docs server at http://127.0.0.1:8000 (your computer) can be done by installing python, and then installing mkdocs.
```bash
> python -m pip install mkdocs
```
To run your local server run the mkdocs module with the `serve` command.
```bash
> cd MonoGame.Extended
MonoGame.Extended> python -m mkdocs serve
INFO - Building documentation...
INFO - Cleaning site directory
[I 170608 01:12:06 server:283] Serving on http://127.0.0.1:8000
[I 170608 01:12:06 handlers:60] Start watching changes
[I 170608 01:12:06 handlers:62] Start detecting changes
[I 170608 01:12:15 handlers:133] Browser Connected: http://127.0.0.1:8000/
```
Now every time you edit a `*.md` file in the `Docs/` folder the site will refresh with the latest info.
To add a new page, you must add Markdown file, and then reference it in the `mkdocs.yml` file somewhere appropriate.
> All pages must be somewhere in the mkdocs.yml `pages` section, otherwise links to it will not work.
-61
View File
@@ -1,61 +0,0 @@
## Animations
The `MonoGame.Extended.Animations` library contains classes useful for 2D [sprite sheet animations](MonoGame.Extended.Animation/Animated-Sprites.md).
With Textures and Sprites we can import Sprite Sheets, collections of mapped images placed on one single file, and draw them on screen through SpriteBatch like any other object on our game. Let's see how we can add "movement" on these sprites using the SpriteSheetAnimation classes from the Animations.SpriteSheets package.
# Choosing what to animate
So let's add a simple character and some sprites to simulate movement. To import the resources using the pipeline, we will need a pair of files here:
The Image file with all the sprites combined in a Map
![](http://i.imgur.com/gVfkoF2.png)
And an xml describing the coordinates and size of each sprite within the map:
```xml
<?xml version="1.0" encoding="utf-8" ?>
<XnaContent>
<Asset Type="System.Collections.Generic.Dictionary[System.String, Microsoft.Xna.Framework.Rectangle]">
<Item><Key>33155_001.png</Key><Value>34 401 31 32</Value></Item>
<Item><Key>33155_002.png</Key><Value>370 349 17 29</Value></Item>
</Asset>
</XnaContent>
```
Hopefully there are a couple of programs to create this file. Once you have those, just throw them inside the Content Pipeline.
![](http://i.imgur.com/hEhyOKh.png)
# Construct the move
Lets initiate our pixels using the Texture imported and then we will use the map to limit and easily access each image.
```csharp
var characterTexture = content.Load<Texture2D>("Sprites/kunio");
var characterMap = content.Load<Dictionary<string, Rectangle>>("Sprites/kunioMap");
var characterAtlas = new TextureAtlas("kunio", characterTexture, characterMap);
var characterAnimationFactory = new SpriteSheetAnimationFactory(characterAtlas);
characterAnimationFactory.Add("idle", new SpriteSheetAnimationData(new[] { 0, 1 }, isLooping: true));
var characterSpriteAnimation = new AnimatedSprite(characterAnimationFactory,"idle");
```
Using a SpriteSheetAnimationFactory we can create Animations and set index of frames included. And passing this to AnimatedSprite we can name an autoplay animation. "idle" is the only one we have for now.
# Drawing the final result
On each update you will need to call the animation to make the transitions between frames.
```csharp
characterSpriteAnimation.Update(deltaSeconds);
```
And finally on Draw the SpriteBatch will do the rest.
```csharp
spriteBatch.Begin();
spriteBatch.Draw(characterSpriteAnimation);
spriteBatch.End();
```
![](http://i.imgur.com/MhEocnH.gif)
-80
View File
@@ -1,80 +0,0 @@
# Bitmap Fonts
Bitmaps fonts generated with the [BMFont](http://www.angelcode.com/products/bmfont/) tool are a great alternative to using the built in `SpriteFont` in MonoGame. There are a couple of reasons you might want to do this, either `SpriteFont`'s are not working out for you or you want to have more control over the fonts in your game.
The `BitmapFont` class in [MonoGame.Extended](https://github.com/craftworkgames/MonoGame.Extended) is designed to be a drop in replacement for the `SpriteFont` class as much as possible. The goal is to take a `.fnt` file and texture generated with the BMFont tool and load it into our game just like any other content.
_bitmapFont = Content.Load<BitmapFont>("my-font");
Then render some text just like any other string.
_spriteBatch.Begin();
_spriteBatch.DrawString(_bitmapFont, "Hello World", new Vector2(100, 200), Color.Red);
_spriteBatch.End();
But before we can do that, we'll need to generate our bitmap font file.
## Generating the font file with BMFont
If you havent already done so, download and install the [BMFont](http://www.angelcode.com/products/bmfont/) tool.
![BMFont tool](bmfont-tool.jpg)
The main window of BMFont displays all of the characters of the font. You'll need to click and drag over the characters to highlight them in white, these are the characters that will be saved to the exported texture. Typically you will take all of the top half and ignore the bottom half, although, you may only want to take a smaller subset to reduce texture size requirements.
To choose a font click **Options** => **Font Settings** or hit the **F** key. You can pretty much choose whatever settings you like here.
![BMFont tool](bmfont-font-settings.jpg)
Close that dialog and make sure all your desired characters are highlighted in white.
Next click **Options** => **Export Options** or hit the **T** key. The important thing here is setting the file format to **XML** and getting the texture width and height right. It's preferable to fit the entire font on a single texture (although not required) and it can sometimes take a little tweaking.
I also recommend using **PNG** textures, **32 bit depth** and the **White text with alpha** preset, but it's up to you. Play around with the settings for different effects.
![BMFont tool](bmfont-export-options.jpg)
Once you're done with the settings you can click **Options** => **Visualize** or hit the **V** key to see a preview of how the texture will be packed.
Finally, click **Options** -> **Save bitmap font as** or hit **Ctrl+S** to export the font file. The textures will also be saved at this location, you'll need to add both of these to your game's content.
## Building the font file with the MonoGame Pipeline
We need to load the font file into the game, but first we need to add a reference to the `MonoGame.Extended.Content.Pipleine.dll` that comes with an importer and processor for BMFont files.
![Reference MonoGame.Extended Pipeline DLL](pipeline-add-references.png)
Once the reference is added, you can add the font file and texture to the content. If all goes well, the importer and processor should be selected automatically.
![MonoGame.Extended BMFont importer](monogame-extended-bmfont-importer-processor.png)
Don't forget to **Rebuild** your content.
## Rendering text in your game
If you've referenced the `MonoGame.Extended.dll` from your game project the code is pretty straightforward.
First load the font into an instance of a `BitmapFont` variable.
_bitmapFont = Content.Load<BitmapFont>("my-font");
Then in your `Draw` method use the `DrawString` extension method to render some text much like you would with a traditional `SpriteFont`.
_spriteBatch.Begin();
_spriteBatch.DrawString(_bitmapFont, "Hello World", new Vector2(50, 50), Color.Red);
_spriteBatch.DrawString(_bitmapFont,
"Contrary to popular belief, Lorem Ipsum is not simply random text.\n\n" +
"It has roots in a piece of classical Latin literature from 45 BC, " +
"making it over 2000 years old. Richard McClintock, a Latin professor" +
" at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin " +
"words, consectetur, from a Lorem Ipsum passage, and going through the cites of " +
"the word in classical literature, discovered the undoubtable source.",
new Vector2(50, 100), new Color(Color.White, 0.5f), _viewportAdapter.VirtualWidth - 50);
_spriteBatch.End();
And observe the result! :)
![MonoGame.Extended Bitmap Fonts](monogame-extended-bitmap-fonts.png)
Happy coding! :)
-58
View File
@@ -1,58 +0,0 @@
# Cameras
## Orthographic Camera
The purpose of the camera is to create a transformation matrix that changes the way a sprite batch is rendered.
To create a camera initialize an instance of it using one of the constructor overloads. It's recommended that you used a viewport adapter to scale the screen but you don't have to.
```csharp
private OrthographicCamera _camera;
protected override void Initialize()
{
base.Initialize();
var viewportAdapter = new BoxingViewportAdapter(Window, GraphicsDevice, 800, 480);
_camera = new OrthographicCamera(viewportAdapter);
}
```
Next you'll need to apply the camera's view matrix to one or more of the `SpriteBatch.Begin` calls in your `Draw` method.
```csharp
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// the camera produces a view matrix that can be applied to any sprite batch
var transformMatrix = _camera.GetViewMatrix();
_spriteBatch.Begin(transformMatrix: transformMatrix);
// ... draw sprites here ...
_spriteBatch.End();
}
```
A [transformation matrix](https://msdn.microsoft.com/en-us/library/ff433701.aspx) is one of the parameters of a `SpriteBatch.Begin` call.
> Transformation matrix for scale, rotate, translate options.
In other words, we use the camera to transform the way a batch of sprites is rendered to the screen without actually modifying their positions, rotations or scales directly. This creates the effect of having a camera looking at your scene that can move, rotate and zoom in and out.
Once you've got a camera instance in your game you'll probably want to move it around in the `Update` method somehow. For example, you could move the camera's position with the arrow keys.
<a name="moveUsage"></a>
```csharp
protected override void Update(GameTime gameTime)
{
var keyboardState = Keyboard.GetState();
const float movementSpeed = 200;
if (keyboardState.IsKeyDown(Keys.Up))
_camera.Move(new Vector2(0, -movementSpeed) * deltaTime);
}
```
Last but not least, there'll be times when you want to convert from screen coordinates to world coordinates and visa-vera. For example, if you want to know which sprite is under the mouse you'll need to convert the mouse position back into the world position that was used to position the sprite in the first place.
```csharp
var mouseState = Mouse.GetState();
_worldPosition = _camera.ScreenToWorld(new Vector2(mouseState.X, mouseState.Y));
```
# Further Reading
[Transformation Matrix on MSDN](https://msdn.microsoft.com/en-us/library/ff433701.aspx)
[Matrix Basics](https://stevehazen.wordpress.com/2010/02/15/matrix-basics-how-to-step-away-from-storing-an-orientation-as-3-angles/)
-55
View File
@@ -1,55 +0,0 @@
# Collections
Collections are extensions to the C# collections that are useful for game programming.
## Bag
A `Bag` is an un-ordered array of items with fast Add and Remove properties.
It is much faster than an array when removing items, and takes less space than a linked list.
Bag will resize itself only when it needs to.
```csharp
var bag = new Bag<int>(3);
bag.Add(4);
bag.Add(8);
bag.Add(15);
// bag is now [4, 8, 15]
bag.Add(16); // array is extended here, capacity is now 4 instead of 3
bag.Remove(1);
// bag is now [4, 16, 15] with a capacity of 4
```
## BitVector32
The `BitVector32` class provides easy access to 32 individual bit flags.
## Deque
Represents a collection of objects which elements can added to or removed either from the front or back; a
[double ended queue](https://en.wikipedia.org/wiki/Double-ended_queue).
## DictionaryExtensions
Extends all `Dictionary<>` classes with `GetValueOrDefault(key, default)`.
## KeyedCollection
A KeyedCollection is used like a `Dictionary<>`, except you provide a function that takes a value and return's it's key.
## ListExtensions
Adds `Shuffle(Random)` to all `IList<>` classes.
## [Object Pooling](Object-Pooling.md)
An `ObjectPool<T>` allows reuse of memory for a group of items to avoid Garbage Collection.
More information is in the [Object Pooling](Object-Pooling.md) documentation.
## ObservableCollection
An `ObservableCollection<T>` manages an `IList<T>` of items firing `ItemAdded`, `ItemRemoved`, `Clearing` and `Cleared` events when the collection is changed.
-3
View File
@@ -1,3 +0,0 @@
## Collisions
The `MonoGame.Extended.Collisions` library contains a 2D grid based collision system.
-3
View File
@@ -1,3 +0,0 @@
## Content.Pipeline
The `MonoGame.Extended.Content.Pipeline` library extends the [MonoGame Content Pipeline tool](http://www.monogame.net/documentation/?page=Pipeline). This adds Animations, BitmapFonts, TextureAtlases, and Tiled maps to the Content Pipeline tool.
-64
View File
@@ -1,64 +0,0 @@
# ContentManager extensions
## ContentManager.OpenStream
`System.IO.Stream ContentManager.OpenStream(string filename)`
**OpenStream** allows easy access to `TitleContainer.OpenStream` so you can use the `Game.Content` object to load compiled resources *and* included resources.
```csharp
// my-file.txt is in the RootDirectory
var stream = Content.OpenStream("my-file.txt");
// do something with file
stream.Close();
```
## ContentManager.GetGraphicsDevice
`GraphicsDevice ContentManager.GetGraphicsDevice()`
**GetGraphicsDevice** returns the current `GraphicsDevice` from the services.
```csharp
var graphicsDevice = Content.GetGraphicsDevice();
var width = graphicsDevice.DisplayMode.Width;
```
# ContentReader extensions
The `ContentReader` extensions help when writing your own content pipeline readers.
## ContentReader.GetGraphicsDevice
`GraphicsDevice ContentManager.GetGraphicsDevice()`
**GetGraphicsDevice** returns the current `GraphicsDevice` to help when loading content for the current display.
```csharp
public class MyTypeReader : ContentTypeReader<MyType> {
protected override MyType Read(ContentReader reader, MyType existingInstance)
{
var graphicsDevice = reader.GetGraphicsDevice();
// ...
}
}
```
## ContentReader.GetRelativeAssetName
`string ContentReader.GetRelativeAssetName(string relativeName)`
**GetRelativeAssetName** helps when your content type loads a different type, and you want to know the name to give `ContentManager.Load`.
```csharp
public class MyTypeReader : ContentTypeReader<MyType> {
protected override MyType Read(ContentReader reader, MyType existingInstance)
{
var assetName = reader.GetRelativeAssetName(reader.ReadString());
var other = reader.ContentManager.Load<OtherType>(assetName);
// ...
}
}
```
-195
View File
@@ -1,195 +0,0 @@
# Entities
The Entities package is a modern high performance Artemis based Entity Component System. Many of the features found in this implementation were inspired by [artemis-odb](https://github.com/junkdog/artemis-odb/). Although, many others were also studied during development. As you'll see the systems are designed to feel familar to MonoGame developers.
## What is an ECS?
An [Entity Component System (ECS)](https://www.gamedev.net/articles/programming/general-and-gameplay-programming/understanding-component-entity-systems-r3013) is a way to build and manage the entities (or game objects) in your game by composing their component parts together. An ECS consists of three main parts:
### Components
A component is simply a class that holds some state about the entity. Typically, components are lightweight and don't contain any game logic. It's common to have components with only a few properties or fields. Components can be more complex but inheritence is not encouraged.
### Entities
An entity is a composition of components identified by an ID. Often you only need the ID of the entity to work with it. For performance reasons, and entity ID is only valid while the entity is alive. Once the entity is destroyed, it's ID may be recycled.
### Systems
A system is a class that will run during the game's `Update` or `Draw` calls. They usually contain the game logic about how to manage a filtered collection of entities and their components.
## Creating the world
The `World` is the entry point to the ECS. It holds your entities and systems and you'll use it later to create and destroy entities.
To create the world you need to use the `WorldBuilder` and add your systems before building the `World` instance.
```csharp
_world = new WorldBuilder()
.AddSystem(new PlayerSystem())
.AddSystem(new RenderSystem(GraphicsDevice))
.Build();
```
*Note:* Manually adding your systems this way might seem annoying at first, but it can be highly desireable to be able to control the order systems are added. It also allows you to constructor inject services as desired.
Once the world is created you need to call the `Update` and `Draw` methods.
```csharp
protected override void Update(GameTime gameTime)
{
_world.Update(gameTime);
base.Update(gameTime);
}
```
```csharp
protected override void Draw(GameTime gameTime)
{
_world.Draw(gameTime);
base.Draw(gameTime);
}
```
*Note:* The world also implements the `IGameComponent` interface, so if you prefer you can add it to the `GameComponentCollection` instead (not to be confused with ECS components).
## Creating entities
Usually when you create an entity you'll want to attach some components to it immediately. This is not required though, as components can be added and removed anytime by systems.
```csharp
var entity = _world.CreateEntity();
entity.Attach(new Transform2(position));
entity.Attach(new Sprite(textureRegion));
```
Any standard class can be used as a component but typically you'll want to keep your components lightweight and specific.
*Note:* An entity can only have one instance of each component type.
## Destroying entities
Removing entities from the world is easy.
```csharp
_world.DestroyEntity(entity);
```
It should be noted that the actual entity creation and removal is deferred until the next update. This allows for some performance optimizations and batches events so that they can be handled more gracefully by systems.
*Note:* When you're inside an `EntitySystem` there are helper methods for creating destroying entities so that you don't need to access the `World` instance each time.
## Types of systems
Systems can be used to do all kinds of processing during your game. There are several kinds of base systems available to build your game.
- An `UpdateSystem` is a basic system that has an `Update` method called every frame.
- A `DrawSystem` is a basic system that has a `Draw` method called every frame.
- An `EntityUpdateSystem` is used to process a filtered collection of entities during the `Update` call.
- An `EntityDrawSystem` is used to process a filtered collection of entities during the `Draw` call.
- An `EntityProcessingSystem` can be used to process a filtered collection of entities one at a time during the `Update` call.
- You can also create a system that has both an `Update` method and a `Draw` method by implementing the `IUpdateSystem` and `IDrawSystem` interfaces respectively.
- An `EntitySystem` is the base class for all entity processing systems. Typically you won't derive from this class unless you're building a new type of entity processing system. If you do derive from this class you probably also want to implement one of the update or draw interfaces.
## Creating systems
To create a new system, decide which base system to derive from and implement a new class.
```csharp
public class RenderSystem : EntityDrawSystem
```
When you're creating entity systems the first thing you'll want to do is provide an `Aspect` to filter the system to only process the entities you're interested in.
For example, a typical `RenderSystem` might want to process entities with a `Sprite` component and a `Transform2` component. To provide an aspect you pass it into the base constructor.
```csharp
public RenderSystem(GraphicsDevice graphicsDevice)
: base(Aspect.All(typeof(Sprite), typeof(Transform2)))
{
_graphicsDevice = graphicsDevice;
_spriteBatch = new SpriteBatch(graphicsDevice);
}
```
Next, you'll need to override the `Update` or `Draw` method (depending on what type of system you're implementing).
In our case, the `Draw` method might look something like this:
```csharp
public override void Draw(GameTime gameTime)
{
_spriteBatch.Begin();
foreach (var entity in ActiveEntities)
{
// draw your entities
}
_spriteBatch.End();
}
```
*Note:* Don't forget to add your system to the `WorldBuilder` when you're done.
## Accessing components
The preferred way to access components is to use component mappers.
A `ComponentMapper` provides a very fast way to access components within a system. When you're using a component mapper you're getting nearly direct access to the underlying arrays that hold the components under the hood.
To get a component mapper, create a field on your system and use the `Initialize` method to grab an instance of the mapper. Do this for each component type you want to process.
```csharp
public override void Initialize(IComponentMapperService mapperService)
{
_transformMapper = mapperService.GetMapper<Transform2>();
_spriteMapper = mapperService.GetMapper<Sprite>();
}
```
Then inside the `Update` or `Draw` method you can get access to the components for each entity you want to process.
```csharp
var transform = _transformMapper.Get(entityId);
var sprite = _spriteMapper.Get(entityId);
_spriteBatch.Draw(sprite, transform);
```
Component mappers can also be used to modify entities on the fly. For example, you can add a new component to an entity with the `Put` method.
```csharp
_buffMapper.Put(entityId, buffComponent);
```
*Note:* The `Put` method will replace an existing component of the same type if it already exists. There is no need to check if the entity already has the component.
You can also check if an entity `Has` a component or `Delete` a component with the mapper.
---
For convienience it's also possible to access components on an entity *without* using component mappers. This can be useful for prototyping ideas or when performance isn't a primary concern.
```csharp
var entity = GetEntity(entityId);
var health = entity.Get<HealthComponent>();
var transform = entity.Get<Transform2>();
```
*Note:* This method of accessing components requires dictionary lookups of the component types each frame. This is still a fairly fast operation, and for some games it'll do just fine.
## Filtering components
An `Aspect` is used by entity systems to decide what component types the system will process. The entities will be available in the system's `ActiveEntities` collection.
An aspect has three methods:
- `Aspect.All(A, B)` requires the entities to have all of the desired components.
- `Aspect.One(C, D)` requires the entities to have any one or more of the components.
- `Aspect.Exclude(E, F)` will exclude entities that have any of these components.
Aspects can also be chained together. For example, an entity matching:
`Aspect.All(A, B).One(C, D).Exclude(E)` would need to have A and B and at least one of C or D except if it has E.
-2
View File
@@ -1,2 +0,0 @@
## Graphics
The `MonoGame.Extended.Graphics` library contains extensions useful for generating dynamic geometry and batching draw calls.
-6
View File
@@ -1,6 +0,0 @@
## Gui
The `MonoGame.Extended.Gui` library contains a complete GUI system. It includes Buttons, Text Boxes, Dialogs and many other controls, and is skinnable.
## NuclexGui
The `MonoGame.Extended.NuclexGui` library contains an implementation of the [Nuclex GUI Framework](https://nuclexframework.codeplex.com/wikipage?title=Nuclex.UserInterface) for XNA, ported to MonoGame.
-50
View File
@@ -1,50 +0,0 @@
## Input
The `MonoGame.Extended.Input` library contains input listener classes that have events you can use to subscribe to input events, instead of having to poll for input changes. It also contains extended keyboard and mouse states.
---
## Input Listeners
There are different events that you can subscribe to in the different input listener classes. Note that this is in the `MonoGame.Extended.Input.InputListeners` library, not just `MonoGame.Extended.Input`.
```c#
// Some example usage
using MonoGame.Extended.Input.InputListeners;
private MouseListener mlistener = new MouseListener;
private void OnMouseMoved(object sender, MouseEventArgs eventArgs) {
// What you want to happen when the mouse is moving
}
protected override void Update(GameTime gameTime)
{
// Subscribe to the event
mlistener.MouseMoved += OnMouseMoved;
mlistener.Update(gameTime);
mlistener.MouseMoved -= OnMouseMoved;
}
```
---
## Extended Keyboard and Mouse States
The library also includes some new methods and properties for the keyboard and mouse states in the `KeyboardStateExtended` and `MouseStateExtended` classes.
```c#
// Some example usage
using MonoGame.Extended.Input;
private KeyboardStateExtended kstate = KeyboardExtended.GetState();
private MouseStateExtended mstate = MouseExtended.GetState();
protected override void Update(GameTime gameTime)
{
if (mstate.PositionChanged()) {
// Code that happens if the position of the mouse changes
else if (kstate.WasAnyKeyJustDown()) {
// Code that happens if there was just any key that was down
}
}
```
The `KeyboardStateExtended` and `MouseStateExtended` classes also contain all of the original methods and properties of the regular `KeyboardState` and `MouseState` classes.
---
## More Player Indexes
The library also adds an extended player index for up to eight players from the `ExtendedPlayerIndex` class. You can access them by typing `ExtendedPlayerIndex.One` up to `ExtendedPlayerIndex.Eight`.
-67
View File
@@ -1,67 +0,0 @@
# Object Pooling
Object pooling is an optimization pattern. It's used to improve performance, in certain cases, by re-using objects instead of allocating memory for them on demand. In C/C++, one the things object pooling has to offer is a solution to avoid [memory fragmentation](http://stackoverflow.com/questions/3770457/what-is-memory-fragmentation). In C#, we don't have to worry about memory fragmentation thanks to [garbage collection](https://msdn.microsoft.com/en-us/library/ee787088). However, garbage collection can be still be too expensive for certain parts of real-time applications, especially on mobile devices with slower CPUs and simpler garbage collectors. [More details on object pooling here](http://gameprogrammingpatterns.com/object-pool.html).
# IMPORTANT
Always profile the game for performance problems!
Using a `Pool<T>` without first profiling for the need of one may result in a *decrease* in performance in certain cases. If you are unsure, don't use the object pooling pattern.
# Creating a Pool-able Object
All objects which can be pooled need to implement the `IPoolable` interface.
The following is a code snippet with comments demonstrating how to implement the interface.
```csharp
private class MyPoolable : IPoolable
{
private ReturnToPoolDelegate _returnAction;
void IPoolable.Initialize(ReturnToPoolDelegate returnAction)
{
// copy the instance reference of the return function so we can call it later
_returnAction = returnAction;
}
public void Return()
{
// check if this instance has already been returned
if (_returnAction != null)
{
// not yet returned, return it now
_returnAction.Invoke(this);
// set the delegate instance reference to null, so we don't accidentally return it again
_returnAction = null;
}
}
}
```
# Using Pooled Objects
## Creating a Pool
Instantiating a `Pool<T>` is similar to any generic collection, i.e `List<T>`, but the pool does require 2 parameters for it's constructor. `T` also has to implement `IPoolable`.
```csharp
var pool = new Pool<MyPoolable>(50, index => new MyPoolable());
```
The first parameter is the _capacity_ of the pool; the maximum number of object instances the pool has reference to. The second parameter is the delegate responsible for creating each object instance.
### NOTE
Having too large of a capacity will waste memory, but having too small of a capacity will limit the number of object instances that can be pooled.
All object instances are created when the pool is instantiated.
## Getting a Pooled Object
A free pooled object instance can be requested from the pool instance.
```csharp
var myPoolable = pool.Request();
```
### NOTE
If the pool is empty, the result will be `null`.
## Returning a Object to the Pool
When the object instance is no longer needed it should be returned to the pool so it can be re-used.
```csharp
myPoolable.Return();
```
-2
View File
@@ -1,2 +0,0 @@
## Particles
The `MonoGame.Extended.Particles` library contains a high performance Particle System ported from the [Mercury Particle Engine](matthew-davey.github.io/mercury-particle-engine/).
-3
View File
@@ -1,3 +0,0 @@
## SceneGraphs
The `MonoGame.Extended.SceneGraphs` library contains a scene graph (tree) system.
-24
View File
@@ -1,24 +0,0 @@
# Screen Management
## Example
The `ScreenGameComponent` manages individual `Screen` objects. Add a new `ScreenGameComponent` to your Game's `Components`, and the screen manager will pass `Initialize` `LoadContent` `UnloadContent` `Update` and `Draw` to every registered screen.
```csharp
public Game1()
{
// Add the screen manager to your Components.
ScreenGameComponent screenGameComponent = new ScreenGameComponent(this);
Components.Add(screenGameComponent);
}
```
To register your class (MyScreen) that subclasses `Screen`. Just pass it into the `Register` function.
```csharp
public Game1()
{
ScreenGameComponent screenGameComponent = new ScreenGameComponent(this);
screenGameComponent.Register(new MyScreen());
Components.Add(screenGameComponent);
}
```
## Demos
[Demos/Features/Demos/ScreensDemo.cs](https://github.com/craftworkgames/MonoGame.Extended/blob/develop/Source/Demos/Features/Demos/ScreensDemo.cs)
-179
View File
@@ -1,179 +0,0 @@
# Serialization
MonoGame.Extended contains various serialization helpers that work with [Newtonsoft Json.NET](http://www.newtonsoft.com/json/help/html/SerializingJSON.htm).
# Json Converters
The following XNA/MonoGame types have converters:
* `Color` via **[ColorJsonConverter](#color-jsonconverter)**
* `Vector2` via **[Vector2JsonConverter](#vector2-jsonconverter)**
The following MonoGame.Extended types have converters:
* `NinePatchRegion2D` via **[NinePatchRegion2DJsonConverter](#ninepatchregion2d-jsonconverter)**
* `Size2` via **[Size2JsonConverter](#size2-jsonconverter)**
* `Range<T>` via **[RangeJsonConverter](#range-jsonconverter)**
* `TextureRegion2D` via **[TextureRegion2DJsonConverter](#textureregion2d-jsonconverter)**
* `Thickness` via **[ThicknessJsonConverter](#thickness-jsonconverter)**
### JsonConverter Example
```csharp
using Newtonsoft.Json;
using Microsoft.Xna.Framework;
using MonoGame.Extended.Serialization;
struct Thing {
public Color BootStrapBlue;
public Vector2 Position;
}
var data = @"{
'BootStrapBlue':'#428bca00',
'Position':'1.1 4',
}";
var thing = JsonConvert.DeserializeObject<Thing>(data,
new ColorJsonConverter(),
new Vector2JsonConverter()
);
thing.BootStrapBlue; // "{R:66 G:139 B:202 A:0}"
thing.Posistion; // "{X:1.1 Y:4}"
```
## Color JsonConverter
ColorJsonConverter tells Newtonsoft Json.NET now to convert string hex values into XNA `Color` objects.
Given the JSON string value
```json
"#10203040"
```
A Color object is created.
```csharp
new Color(16, 32, 48, 64);
```
The format is a `#` followed by byte hex codes for Red, Green, Blue, and Alpha channels.
## Vector2 JsonConverter
Vector2JsonConverter tells Newtonsoft Json.NET how to serialize XNA `Vector2` objects.
Given the JSON string value
```JSON
"1.2 33"
```
A new Vector2 is created.
```csharp
new Vector2(1.2f, 33f);
```
The format is `X Y` for the x and y components of a 2D vector.
## NinePatchRegion2D JsonConverter
NinePatchRegion2DJsonConverter tells Newtonsoft Json.NET how to serialize MonoGame.Extended `NinePatchRegion2D` objects.
Given the JSON object value
```json
{"TextureRegion":"Center","Padding":"1 2 3 4"}
```
A new NinePatchRegion2D is created and the TextureRegion is looked up in the TextureRegionService.
```csharp
new NinePatchRegion2D(TextureRegion2D('Center',...), 1, 2, 3, 4)
```
The format is not a string value, but a nested JSON object where `Padding` is a `Thickness` value.
## Size2 JsonConverter
Size2JsonConverter tells Newtonsoft Json.NET how to serialize MonoGame.Extended `Size2` objects.
Given the JSON string value
```json
"10 4"
```
A new Size2 object is created. Understood, good buddy.
```csharp
new Size2(10f, 4f)
```
The format is a JSON string containing the Width, and Height values as decimal numbers.
## Range JsonConverter
`RangeJsonConverter<T>` tells Newtonsoft Json.NET how to serialize MonoGame.Extended `Range<T>` objects.
Given the JSON string value
```json
"1 9000"
```
A new Range<T> object is created.
```csharp
new Range<int>(1, 9000);
```
The format is a JSON string containing one or two values.
## TextureRegion2D JsonConverter
TextureRegion2DJsonConverter tells Newtonsoft Json.NET how to serialize MonoGame.Extended `TextureRegion2D` objects.
Given the JSON string value
```json
"Center"
```
The TextureRegionService is queried with `GetTextureRegion("Center")`
The format is a JSON string with the name of the TextureRegion in a TextureAtlas.
## Thickness JsonConverter
ThicknessJsonConverter tells Newtonsoft Json.NET how to serialize a MonoGame.Extended `Thickness` object.
Given the JSON string value
```json
"1 2 3 4"
```
A new Thickness object is created.
```
Thickness.Parse("1 2 3 4")
```
The format is a JSON string containing a value to be parsed by Thickness.
* `"1 2 3 4"` is left:1, top:2, right:3, bottom:4
* `"2 4"` is left:2, top:4, right:2, bottom:4
* `"8"` is left:8, top:8, right:8, bottom:8
* `"1,2"` is left:1, top:2, right:1, top:2
# Extensions
## ReadAsMultiDimensional
`Newtonsoft.Json.JsonReader` is extended with `T[] ReadAsMultiDimensional<T>()`
This allows you to easily create a custom JsonConverter with a list of values.
For example a list of floats
```json
"1.1 2.3 4.5 6.1"
```
Could be parsed into an array of floats using the following JsonConverter that uses `ReadAsMultiDimensional`
```csharp
public class PathJsonConverter : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object value, JsonSerializer serializer)
{
float[] path = reader.ReadAsMultiDimensional<float>();
return path;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var path = (float[]) value;
writer.WriteValue(string.Join(" ", path));
}
}
```
-545
View File
@@ -1,545 +0,0 @@
<a alight="right" href="https://www.mapeditor.org/"><img align="right" src="https://raw.githubusercontent.com/bjorn/tiled/master/src/tiled/images/about-tiled-logo.png" height="200"></a>
# Tiled
The `MonoGame.Extended.Tiled` library loads and renders maps created with the popular [Tiled Map Editor](http://www.mapeditor.org/).
Tiled is an [open sourced](https://github.com/bjorn/tiled) free to use "generic tile map editor". Tiled lets you easily design and view tile maps, and through the `Monogame.Extended.Tiled` package, you can load and display a map generated with Tiled in monogame
To load a TiledMap into your project, you first need to add it to your `ContentManager`, and in order to compile the tile map for use in `MonoGame` you must add a reference to the pipeline tool.
Instructions to do so can be found [here](http://docs.monogameextended.net/Installation/#installation)
# Using the map in your game
The first thing you will need to do is to add the library your reference like this
```c#
// The tiled map parts
using MonoGame.Extended.Tiled;
// The tile renderers
using MonoGame.Extended.Tiled.Renderers;
```
Its recomended to use a camera aswell when you use tiled maps
```c#
// To get the camera
using MonoGame.Extended;
// Then you need a viewport adapter
using MonoGame.Extended.ViewportAdapters;
// The camera object
private OrthographicCamera camera;
```
To get a map to render you will need 2 new properties
```c#
// The tile map
private TiledMap map;
// The renderer for the map
private TiledMapRenderer mapRenderer;
```
Now we want to initialize the things, you can do this in either the `Initialize()` or `LoadContent()` methods
```c#
protected override void Initialize()
{
base.Initialize();
// Load the map
map = Content.Load<TiledMap>("path/to/your/map/file");
// Create the map renderer
mapRenderer = new TiledMapRenderer(GraphicsDevice, map);
// If you decided to use the camere, then you could also initialize it here like this
var viewportadapter = new BoxingViewportAdapter(Window, GraphicsDevice, 800, 600);
camera = new OrthographicCamere(viewportadapter);
}
```
Now after all this we will need to update and draw the mapRenderer, we do this in the `Update()` and `Draw()` methods like this
```c#
protected override void Update(GameTime gameTime)
{
// Update the map renderer
mapRenderer.Update(gameTime);
// If you used the camera then we update it aswell
camera.LookAt(new Vector2(0, 0));
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
// Clear the screen
GraphicsDevice.Clear(Color.White);
// Transform matrix is only needed if you have a camera
// Setting the sampler state to `new SamplerState { Filter = TextureFilter.Point }` will reduce gaps and odd artifacts when using animated tiles
spriteBatch.Begin(transformMatrix: camera.GetViewMatrix(), samplerState: new SamplerState { Filter = TextureFilter.Point });
// Then we will render the map
mapRenderer.Draw(camera.GetViewMatrix());
// End the sprite batch
spriteBatch.End();
base.Draw(gameTime);
}
```
# Help with the many things
Here we will just go into what some of the functions do
The `TiledMap`, this is what contains the map data generated by `Tiled`, this will contain all the diffrent layers and tilesets that your map uses.
The `TiledMapTileLayer`, this is what contains the array of id's that tell your renderer what to draw at specific locations, they will generally be usefull for drawing the environment.
But can also be used for simple collision detection.
The `TiledMapObjectLayer`, this is what contains all the data for your many map objects, this will generally be usefull for things like telling where to spawn the player, what happens when something is over it and so on.
The `TiledMapRenderer`, this is what draws your map, simple as that.
# Some examples for this
If you are still not sure how you can use this, you may want to look at some example code, and here you will get just that!
Simple collision handler
```c#
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using MonoGame.Extended;
using MonoGame.Extended.Animations;
using MonoGame.Extended.Animations.SpriteSheets;
using MonoGame.Extended.Sprites;
using MonoGame.Extended.TextureAtlases;
using MonoGame.Extended.Tiled;
using MonoGame.Extended.Tiled.Renderers;
using MonoGame.Extended.ViewportAdapters;
namespace MapCollisions
{
// Control states to determine what animation to play
public enum PlayerStates
{
Up,
Down,
Left,
Right,
Idle,
}
public class Player
{
private readonly AnimatedSprite sprite; // The sprite
private float _directionX = 0.0f; // The left and right direction
private float _directionY = 0.0f; // The up and down direction
private PlayerStates state;
private Transform2 transform;
private const float movementSpeed = 4f; // How fast the player moves
private const int minimumDistance = 8; // The minimum distance the player can be from a wall
public RectangleF BoundingBox => sprite.GetBoundingRectangle(transform.Position, transform.Rotation, transform.Scale);
public Vector2 Position
{
get { return transform.Position; }
set { transform.Position = value; }
}
// Update the playerstate
public PlayerStates State
{
get { return state; }
private set
{
if (state != value)
{
state = value;
switch (state)
{
case PlayerStates.Up:
sprite.Play("WalkUp", () => State = PlayerStates.Idle);
break;
case PlayerStates.Down:
sprite.Play("WalkDown", () => State = PlayerStates.Idle);
break;
case PlayerStates.Left:
sprite.Play("WalkLeft", () => State = PlayerStates.Idle);
break;
case PlayerStates.Right:
sprite.Play("WalkRight", () => State = PlayerStates.Idle);
break;
case PlayerStates.Idle:
sprite.Play("Idle");
break;
}
}
}
}
// The player constructor
public Player(SpriteSheetAnimationFactory animations, Vector2 startposition)
{
sprite = new AnimatedSprite(animations);
transform = new Transform2();
Position = startposition;
State = PlayerStates.Idle;
}
// Check for if the player can go to the location
public bool CanGoTo(TiledMapTileLayer tileLayer)
{
TiledMapTile? tile;
if (_directionX != 0.0f && _directionY != 0.0f)
{
if (_directionX < 0.0f)
{
if (_directionY < 0.0f)
{
ushort tx = (ushort)((Position.X - minimumdist) / tileLayer.TileWidth);
ushort ty = (ushort)((Position.Y + minimumdist) / tileLayer.TileHeight);
tileLayer.TryGetTile(tx, ty, out tile);
if (!tile.Value.IsBlank)
{
return false;
}
else
{
return true;
}
}
else
{
ushort tx = (ushort)((Position.X - minimumdist) / tileLayer.TileWidth);
ushort ty = (ushort)((Position.Y - minimumdist) / tileLayer.TileHeight);
tileLayer.TryGetTile(tx, ty, out tile);
if (!tile.Value.IsBlank)
{
return false;
}
else
{
return true;
}
}
}
else
{
if (_directionY < 0.0f)
{
ushort tx = (ushort)((Position.X + minimumdist) / tileLayer.TileWidth);
ushort ty = (ushort)((Position.Y + minimumdist) / tileLayer.TileHeight);
tileLayer.TryGetTile(tx, ty, out tile);
if (!tile.Value.IsBlank)
{
return false;
}
else
{
return true;
}
}
else
{
ushort tx = (ushort)((Position.X + minimumdist) / tileLayer.TileWidth);
ushort ty = (ushort)((Position.Y - minimumdist) / tileLayer.TileHeight);
tileLayer.TryGetTile(tx, ty, out tile);
if (!tile.Value.IsBlank)
{
return false;
}
else
{
return true;
}
}
}
}
else if (_directionX != 0.0f)
{
if (_directionX < 0.0f)
{
ushort tx = (ushort)((Position.X - minimumdist) / tileLayer.TileWidth);
ushort ty = (ushort)(Position.Y / tileLayer.TileHeight);
tileLayer.TryGetTile(tx, ty, out tile);
if (!tile.Value.IsBlank)
{
return false;
}
else
{
return true;
}
}
else
{
ushort tx = (ushort)((Position.X + minimumdist) / tileLayer.TileWidth);
ushort ty = (ushort)(Position.Y / tileLayer.TileHeight);
tileLayer.TryGetTile(tx, ty, out tile);
if (!tile.Value.IsBlank)
{
return false;
}
else
{
return true;
}
}
}
else
{
if (_directionY < 0.0f)
{
ushort tx = (ushort)(Position.X / tileLayer.TileWidth);
ushort ty = (ushort)((Position.Y + minimumdist) / tileLayer.TileHeight);
tileLayer.TryGetTile(tx, ty, out tile);
if (!tile.Value.IsBlank)
{
return false;
}
else
{
return true;
}
}
else
{
ushort tx = (ushort)(Position.X / tileLayer.TileWidth);
ushort ty = (ushort)((Position.Y - minimumdist) / tileLayer.TileHeight);
tileLayer.TryGetTile(tx, ty, out tile);
if (!tile.Value.IsBlank)
{
return false;
}
else
{
return true;
}
}
}
}
// Update the controls
public void ControlUpdate(KeyboardState keyboardstate, KeyboardState oldkeyboardstate, GamePadState gamepadstate, GamePadState oldgamepadstate)
{
if (keyboardstate.IsKeyDown(Keys.W) ||
keyboardstate.IsKeyDown(Keys.Up) ||
gamepadstate.DPad.Up == ButtonState.Pressed)
{
this.Walk(0.0f, 1.0f);
}
else if (keyboardstate.IsKeyDown(Keys.S) ||
keyboardstate.IsKeyDown(Keys.Down) ||
gamepadstate.DPad.Down == ButtonState.Pressed)
{
this.Walk(0.0f, -1.0f);
}
else if (keyboardstate.IsKeyDown(Keys.A) ||
keyboardstate.IsKeyDown(Keys.Left) ||
gamepadstate.DPad.Left == ButtonState.Pressed)
{
this.Walk(-1.0f, 0.0f);
}
else if (keyboardstate.IsKeyDown(Keys.D) ||
keyboardstate.IsKeyDown(Keys.Right) ||
gamepadstate.DPad.Right == ButtonState.Pressed)
{
this.Walk(1.0f, 0.0f);
}
else
{
this.Walk(0.0f, 0.0f);
}
}
// Update the player location
public void Update(GameTime gameTime, TiledMapTileLayer tileLayer)
{
sprite.Update(gameTime);
if (State == PlayerState.Down)
{
if (CanGoTo(tileLayer) is true)
{
Position = new Vector2(Position.X, Position.Y + movementSpeed);
}
else
{
State = PlayerState.Idle;
}
}
if (State == PlayerState.Left)
{
if (CanGoTo(tileLayer) is true)
{
Position = new Vector2(Position.X - movementSpeed, Position.Y);
}
else
{
State = PlayerState.Idle;
}
}
if (State == PlayerState.Right)
{
if (CanGoTo(tileLayer) is true)
{
Position = new Vector2(Position.X + movementSpeed, Position.Y);
}
else
{
State = PlayerState.Idle;
}
}
if (State == PlayerState.Up)
{
if (CanGoTo(tileLayer) is true)
{
Position = new Vector2(Position.X, Position.Y - movementSpeed);
}
else
{
State = PlayerState.Idle;
}
}
}
// Draw the player
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(sprite, transform);
}
// Walk function to change state
public void Walk(float directionX, float directionY)
{
_directionX = directionX;
_directionY = directionY;
if (_directionX != 0.0f && _directionY == 0.0f)
{
if (_directionX < 0.0f)
{
State = PlayerState.Left;
}
else
{
State = PlayerState.Right;
}
}
else if (_directionX == 0.0f && _directionY != 0.0f)
{
if (_directionY < 0.0f)
{
State = PlayerState.Down;
}
else
{
State = PlayerState.Up;
}
}
else
{
State = PlayerState.Idle;
}
}
}
public class Game1 : Game
{
private readonly GraphicsDeviceManager graphics;
private SpriteBatch spriteBatch;
private OrthographicCamera camera;
private TiledMap map;
private TiledMapTileLayer mapCollisions;
private TiledMapRenderer mapRenderer;
private Player player;
private KeyboardState keyboard;
private GamePadState gamepad;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
var viewportAdapter = new BoxingViewportAdapter(Window, GraphicsDevice, 800, 600);
camera = new OrthographicCamera(viewportAdapter);
var playeranimations = Content.Load<SpriteSheetAnimationFactory>("playeranimations");
map = Content.Load<TiledMap>("world");
mapRenderer = new TiledMapRenderer(GraphicsDevice, map);
mapCollisions = map.GetLayer<TiledMapLayer>("Collisions");
var start = map.GetLayer<TiledMapObjectLayer>("Objects").Objects[1].Position;
player = new Player(playeranimations, start);
}
protected override void UnloadContent()
{
}
protected override void Update(GameTime gameTime)
{
var keyboardstate = Keyboard.GetState();
var gamepadstate = GamePad.GetState(PlayerIndex.One);
if (keyboardstate.IsKeyDown(Keys.Excape) || gamepadstate.Buttons.Back == ButtonState.Pressed)
{
Exit();
}
player.ControlUpdate(keyboardstate, keyboard, gamepadstate, gamepad);
player.Update(gameTime);
mapRenderer.Update(gameTime);
camera.LookAt(player.Position);
keyboard = keyboardstate;
gamepad = gamepadstate;
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
spriteBatch(transformMatrix: camera.GetViewMatrix(), samplerState: new SamplerState { Filter = TextureFilter.Point});
mapRenderer.Draw(camera.GetViewMatrix());
player.Draw(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
}
public static class Program
{
[STAThread]
static void Main()
{
using (var game = new Game1())
game.Run();
}
}
}
```
Good luck and happy coding :)
-3
View File
@@ -1,3 +0,0 @@
## Tweening
The `MonoGame.Extended.Tweening` library contains class extensions for tween based animations.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 168 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

-44
View File
@@ -1,44 +0,0 @@
# Installation
MonoGame.Extended is a collection of [.NET Standard libraries](https://docs.microsoft.com/en-us/dotnet/standard/net-standard) designed to be referenced from any MonoGame project to add common extensions and classes for making your games more awesome.
The libraries are distributed as [NuGet packages](https://www.nuget.org/packages?q=MonoGame.Extended) and can be installed using the NuGet Package Manager in [Visual Studio](https://www.visualstudio.com), [Visual Studio for Mac](https://visualstudio.microsoft.com/vs/mac/), or [MonoDevelop](http://www.monodevelop.com). They can also be installed by running the following command (or the equivalent command for the package you want to install) in the [Package Manager Console](http://docs.nuget.org/consume/package-manager-console).
Install-Package MonoGame.Extended
Note that [MonoGame 3.6 will need to be installed](http://www.monogame.net/downloads/) to properly use MonoGame.Extended in your game project.
## Referencing the Content Pipeline extension
To get the full experience you'll also want to install the Content Pipeline extension:
Install-Package MonoGame.Extended.Content.Pipeline
This package is not included in MonoGame.Extended and must be installed separately. It won't add any references to your project. Instead it will download a DLL that's intended to be referenced from the [MonoGame Content Pipeline tool](http://www.monogame.net/documentation/?page=Pipeline).
You'll need to manually add the reference to your content file (usually `Content.mgcb`) using one of the following methods.
### Using the MonoGame Pipeline GUI
To add the reference using the Pipeline GUI tool follow these steps:
1. Click on the **Content** node in the root of the tree.
2. In the properties window, modify the **References** property.
3. Find and add the `MonoGame.Extended.Content.Pipeline.dll`. It's usually located in the **packages** folder of your solution. The default location of the **packages** folder in .NET Core is: C:\Users\[User]\.nuget\packages.
![MonoGame Pipeline Add References](https://dl.dropboxusercontent.com/u/82020056/MonoGame.Extended/how-to-add-content-pipeline-reference.png)
### Using a text editor
An alternative way to add the reference is by manually editing the `Content.mgcb` file in a text editor or Visual Studio. Look for the references section and update it like this:
```
#-------------------------------- References --------------------------------#
/reference:..\..\packages\MonoGame.Extended.Content.Pipeline.0.6.372\tools\MonoGame.Extended.Content.Pipeline.dll
```
**Remember:** The `MonoGame.Extended.dll` and the `MonoGame.Extended.Content.Pipeline.dll` come as a pair. Always make sure the version referenced by your game matches the version referenced by the Pipeline tool.
That's it! Once you've referenced the library you can start using it to make your games even more awesome.
-14
View File
@@ -1,14 +0,0 @@
# Pre-Release NuGet packages
You can get access to the pre-release NuGet packages by adding the [Craftwork Games Build Server](http://build.craftworkgames.com/guestAuth/app/nuget/v1/FeedService.svc/) as a NuGet package source in Visual Studio.
![Craftwork Games Build Server NuGet Package Source](https://dl.dropboxusercontent.com/u/82020056/craftwork-games-build-server-nuget-package-source.png)
## Instructions
1. In Visual Studio go to Tools => NuGet Package Manager => Package Manager Settings => Package Sources
2. Add a new package source using the following url `http://build.craftworkgames.com/guestAuth/app/nuget/v1/FeedService.svc/`
3. When you're adding the package, remember to tick the "Include prerelease" checkbox
![Include prerelease](https://dl.dropboxusercontent.com/u/82020056/install-monogame-extended-nuget-package-include-prerelease.png)
-25
View File
@@ -1,25 +0,0 @@
# Showcase
## [Super Pete the Pirate](http://community.monogame.net/t/super-pete-the-pirate/8537)
[![Super Pete the Pirate](http://community.monogame.net/uploads/default/optimized/2X/b/be722c768e02881aa36c9f01f8225771aec19c3c_1_690x460.png)](https://www.youtube.com/watch?v=bf1jcjTle6A)
In the game you control Pete, a captain that is in your adventure at the sea. In the middle of the travel, his ship is looted by other pirates inside a dense mist. They take a very important thing to Pete: his hat. Pete is put on the board and is expelled from his ship. After the mist, Pete reaches a coast and decides to explore it, but something happens: he found the pirates that are with his hat! Now Pete want to recover his hat no matter what happens.
Watch the [gameplay video](https://www.youtube.com/watch?v=bf1jcjTle6A).
## [Winter Defense](https://www.youtube.com/watch?v=13CJ6jiPTQs&feature=youtu.be)
In this game you control a penguin that must save the winter crystal, which is being attacked by creatures that want to destroy it. The game was built in C# using MonoGame to a game jam.
## [The Attack of Goop](https://www.youtube.com/watch?v=n5-0MEDyu7k)
Game created to the Kolks Game Jam, made with MonoGame.
## [Tiles](http://store.steampowered.com/app/594750/)
Tiles is a unique action-puzzle game that will both convolute your mind and burn your finger tips!
## [MonoGame - Engines, Frameworks & More](https://www.youtube.com/watch?v=TFriP9z9qKQ)
DDReaper talks about the framework in his youtube video around the 10 minute mark.
View File
View File
View File
View File
View File
View File
View File
-37
View File
@@ -1,37 +0,0 @@
# Sprites
A sprite in computer graphics terms most often refers to an image drawn to the screen in a 2D game. A sprite can be a single image, but quite often you'll want sprites to be animated.
## Drawing Basic Sprites
![apple](images/sprites/apple.png)
<small>source: [gamedevmarket.net](https://www.gamedevmarket.net/asset/icons-food-9999/?ally=yJRl98tX)</small>
Drawing a basic sprite with MonoGame can be done using the `SpriteBatch`. First, load a `Texture2D` with the `ContentManager` in the `LoadContent` method.
```cs
protected override void LoadContent()
{
_spriteBatch = new SpriteBatch(GraphicsDevice);
_apple = Content.Load<Texture2D>("apple");
}
```
Then, in the `Draw` method you can draw the texture between the `Begin` and `End` calls of the `SpriteBatch`.
```cs
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
_spriteBatch.Begin();
_spriteBatch.Draw(_apple, new Vector2(100, 100), Color.White);
_spriteBatch.End();
base.Draw(gameTime);
}
```
Drawing sprites directly from the `Texture2D` can be useful in certain scenarios, like drawing backgrounds, but it can be quite limiting when you want to do animations.
View File
View File
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 900 B

-25
View File
@@ -1,25 +0,0 @@
# Welcome
Welcome to the documentation for [MonoGame.Extended](https://github.com/craftworkgames/MonoGame.Extended), a collection of NuGet packages that make [MonoGame](http://www.monogame.net/) more awesome.
We're only just getting started building this documentation. If you're not finding what you're looking for we've got a number of other places to get help.
- We've got a live chatroom on [Discord](https://discord.gg/xPUEkj9)
- We've got our own section on the [MonoGame Community Forums](http://community.monogame.net/c/extended)
- Development is usually discussed in [github issues](https://github.com/craftworkgames/MonoGame.Extended/issues)
- We've even got a [tag on stackoverflow](http://gamedev.stackexchange.com/questions/tagged/monogame-extended) ;)
# Getting Started
- [Installation](installation.md)
# About
MonoGame.Extended is an open source extension library for [MonoGame](http://www.monogame.net/). A collection of classes and extensions to make it easier to make games with MonoGame.
The goal of the project is to provide a wide variety of features often needed when making games with MonoGame without being a complete game engine. Most of the features in MonoGame.Extended are isolated into different namespaces. You can pick and choose which bits you want and which bits you don't. It's designed to get you going fast and stay out of your way.
The core library is built as a Portable Class Library (PCL) that contains one code base for all supported platforms. PCL's are fully supported by [Visual Studio 2015 on Windows](https://msdn.microsoft.com/en-us/library/gg597391(v=vs.110).aspx), [Xamarin Studio](https://developer.xamarin.com/guides/cross-platform/application_fundamentals/pcl/introduction_to_portable_class_libraries/) for Android and iOS and have also been reported to work on Linux and Mac. This means that a single self contained library can be used to target a wide variety of platforms.
MonoGame.Extended also provides another DLL that is to be used with the [MonoGame Pipeline tool](http://www.monogame.net/documentation/?page=Pipeline). This provides a set of extra content importers and processors that can be used to load extra content for your game. The content is processed into XNB files just like your textures and sounds and loaded into your games using the standard `Content.Load` method.
-6
View File
@@ -1,6 +0,0 @@
site_name: MonoGame.Extended
edit_uri: edit/develop/Docs/
theme:
name: 'readthedocs'
repo_url: https://github.com/craftworkgames/MonoGame.Extended