Browse Source

Add the collision example code (#20)

* Add the collision example code

* Remove the requirement to pass down game to get access to random
Jeremy Swartwood 1 year ago
parent
commit
7a64ffaf94

+ 25 - 0
src/DocumentationSamples/Collision/Collision.sln

@@ -0,0 +1,25 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 17
+VisualStudioVersion = 17.11.35303.130
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Collision", "Collision\Collision.csproj", "{C239165A-DC80-49B6-83E9-073B485A8E06}"
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|Any CPU = Debug|Any CPU
+		Release|Any CPU = Release|Any CPU
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{C239165A-DC80-49B6-83E9-073B485A8E06}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{C239165A-DC80-49B6-83E9-073B485A8E06}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{C239165A-DC80-49B6-83E9-073B485A8E06}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{C239165A-DC80-49B6-83E9-073B485A8E06}.Release|Any CPU.Build.0 = Release|Any CPU
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+	GlobalSection(ExtensibilityGlobals) = postSolution
+		SolutionGuid = {2349FEA0-7293-4258-A0FA-C997A5CD08FC}
+	EndGlobalSection
+EndGlobal

+ 36 - 0
src/DocumentationSamples/Collision/Collision/.config/dotnet-tools.json

@@ -0,0 +1,36 @@
+{
+  "version": 1,
+  "isRoot": true,
+  "tools": {
+    "dotnet-mgcb": {
+      "version": "3.8.2.1105",
+      "commands": [
+        "mgcb"
+      ]
+    },
+    "dotnet-mgcb-editor": {
+      "version": "3.8.2.1105",
+      "commands": [
+        "mgcb-editor"
+      ]
+    },
+    "dotnet-mgcb-editor-linux": {
+      "version": "3.8.2.1105",
+      "commands": [
+        "mgcb-editor-linux"
+      ]
+    },
+    "dotnet-mgcb-editor-windows": {
+      "version": "3.8.2.1105",
+      "commands": [
+        "mgcb-editor-windows"
+      ]
+    },
+    "dotnet-mgcb-editor-mac": {
+      "version": "3.8.2.1105",
+      "commands": [
+        "mgcb-editor-mac"
+      ]
+    }
+  }
+}

+ 51 - 0
src/DocumentationSamples/Collision/Collision/BallEntity.cs

@@ -0,0 +1,51 @@
+// Copyright (c) Craftwork Games. All rights reserved.
+// Licensed under the MIT license.
+// See LICENSE file in the project root for full license information.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using Microsoft.Xna.Framework.Graphics;
+using Microsoft.Xna.Framework;
+using MonoGame.Extended.Collisions;
+using MonoGame.Extended;
+
+namespace Collision
+{
+    public class BallEntity : IEntity
+    {
+        public Vector2 Velocity;
+        public IShapeF Bounds { get; }
+
+        public BallEntity(CircleF circleF)
+        {
+            Bounds = circleF;
+            RandomizeVelocity();
+        }
+
+        public void Draw(SpriteBatch spriteBatch)
+        {
+            spriteBatch.DrawCircle((CircleF)Bounds, 8, Color.Red, 3f);
+        }
+
+        public void Update(GameTime gameTime)
+        {
+            Bounds.Position += Velocity * gameTime.GetElapsedSeconds() * 30;
+        }
+
+        public void OnCollision(CollisionEventArgs collisionInfo)
+        {
+            RandomizeVelocity();
+            Bounds.Position -= collisionInfo.PenetrationVector;
+        }
+
+
+        private void RandomizeVelocity()
+        {
+            Velocity.X = Random.Shared.Next(-1, 2);
+            Velocity.Y = Random.Shared.Next(-1, 2);
+        }
+    }
+}

+ 38 - 0
src/DocumentationSamples/Collision/Collision/Collision.csproj

@@ -0,0 +1,38 @@
+<Project Sdk="Microsoft.NET.Sdk">
+  <PropertyGroup>
+    <OutputType>WinExe</OutputType>
+    <TargetFramework>net8.0</TargetFramework>
+    <RollForward>Major</RollForward>
+    <PublishReadyToRun>false</PublishReadyToRun>
+    <TieredCompilation>false</TieredCompilation>
+  </PropertyGroup>
+  <PropertyGroup>
+    <MonoGameExtendedPipelineReferencePath>$(MSBuildThisFileDirectory)pipeline-references</MonoGameExtendedPipelineReferencePath>
+  </PropertyGroup>
+  <PropertyGroup>
+    <ApplicationManifest>app.manifest</ApplicationManifest>
+    <ApplicationIcon>Icon.ico</ApplicationIcon>
+  </PropertyGroup>
+  <ItemGroup>
+    <None Remove="Icon.ico" />
+    <None Remove="Icon.bmp" />
+  </ItemGroup>
+  <ItemGroup>
+    <EmbeddedResource Include="Icon.ico">
+      <LogicalName>Icon.ico</LogicalName>
+    </EmbeddedResource>
+    <EmbeddedResource Include="Icon.bmp">
+      <LogicalName>Icon.bmp</LogicalName>
+    </EmbeddedResource>
+  </ItemGroup>
+  <ItemGroup>
+    <PackageReference Include="MonoGame.Extended" Version="4.0.3" />
+    <PackageReference Include="MonoGame.Extended.Content.Pipeline" Version="4.0.3" />
+    <PackageReference Include="MonoGame.Framework.DesktopGL" Version="3.8.2.1105" />
+    <PackageReference Include="MonoGame.Content.Builder.Task" Version="3.8.2.1105" />
+  </ItemGroup>
+  <Target Name="RestoreDotnetTools" BeforeTargets="Restore">
+    <Message Text="Restoring dotnet tools" Importance="High" />
+    <Exec Command="dotnet tool restore" />
+  </Target>
+</Project>

+ 15 - 0
src/DocumentationSamples/Collision/Collision/Content/Content.mgcb

@@ -0,0 +1,15 @@
+
+#----------------------------- Global Properties ----------------------------#
+
+/outputDir:bin/$(Platform)
+/intermediateDir:obj/$(Platform)
+/platform:DesktopGL
+/config:
+/profile:Reach
+/compress:False
+
+#-------------------------------- References --------------------------------#
+
+
+#---------------------------------- Content ---------------------------------#
+

+ 51 - 0
src/DocumentationSamples/Collision/Collision/CubeEntity.cs

@@ -0,0 +1,51 @@
+// Copyright (c) Craftwork Games. All rights reserved.
+// Licensed under the MIT license.
+// See LICENSE file in the project root for full license information.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using Microsoft.Xna.Framework.Graphics;
+using Microsoft.Xna.Framework;
+using MonoGame.Extended.Collisions;
+using MonoGame.Extended;
+
+namespace Collision
+{
+    public class CubeEntity : IEntity
+    {
+        public Vector2 Velocity;
+        public IShapeF Bounds { get; }
+
+        public CubeEntity(RectangleF rectangleF)
+        {
+            Bounds = rectangleF;
+            RandomizeVelocity();
+        }
+
+        public virtual void Draw(SpriteBatch spriteBatch)
+        {
+            spriteBatch.DrawRectangle((RectangleF)Bounds, Color.Red, 3);
+        }
+
+        public virtual void Update(GameTime gameTime)
+        {
+            Bounds.Position += Velocity * gameTime.GetElapsedSeconds() * 50;
+        }
+
+        public void OnCollision(CollisionEventArgs collisionInfo)
+        {
+            Velocity.X *= -1;
+            Velocity.Y *= -1;
+            Bounds.Position -= collisionInfo.PenetrationVector;
+        }
+
+        private void RandomizeVelocity()
+        {
+            Velocity.X = Random.Shared.Next(-1, 2);
+            Velocity.Y = Random.Shared.Next(-1, 2);
+        }
+    }
+}

+ 103 - 0
src/DocumentationSamples/Collision/Collision/Game1.cs

@@ -0,0 +1,103 @@
+// Copyright (c) Craftwork Games. All rights reserved.
+// Licensed under the MIT license.
+// See LICENSE file in the project root for full license information.
+
+using System.Collections.Generic;
+using System;
+using Microsoft.Xna.Framework;
+using Microsoft.Xna.Framework.Graphics;
+using Microsoft.Xna.Framework.Input;
+using MonoGame.Extended.Collisions;
+using MonoGame.Extended;
+
+namespace Collision
+{
+    public class Game1 : Game
+    {
+        // Monogame core related
+        private GraphicsDeviceManager _graphics;
+        private SpriteBatch _spriteBatch;
+
+        // Monogame.Extended.Collisions example related
+        private readonly List<IEntity> _entities = new List<IEntity>();
+        private readonly CollisionComponent _collisionComponent;
+        const int MapWidth = 500;
+        const int MapHeight = 500;
+
+        public Game1()
+        {
+            _graphics = new GraphicsDeviceManager(this);
+            Content.RootDirectory = "Content";
+            IsMouseVisible = true;
+
+            // Monogame.Extended.Collisions example related
+            _collisionComponent = new CollisionComponent(new RectangleF(0, 0, MapWidth, MapHeight));
+        }
+
+        protected override void Initialize()
+        {
+            base.Initialize();
+
+            // Create some objects to use in the collision demo
+            for (var i = 0; i < 50; i++)
+            {
+                var size = Random.Shared.Next(20, 40);
+                var position = new Vector2(Random.Shared.Next(-MapWidth, MapWidth * 2), Random.Shared.Next(0, MapHeight));
+                if (i % 2 == 0)
+                {
+                    _entities.Add(new BallEntity(new CircleF(position, size)));
+                }
+                else
+                {
+                    _entities.Add(new CubeEntity(new RectangleF(position, new SizeF(size, size))));
+                }
+            }
+
+            // Add those objects to the collisionComponent so it will do the collision checking for us
+            foreach (IEntity entity in _entities)
+            {
+                _collisionComponent.Insert(entity);
+            }
+        }
+
+        protected override void LoadContent()
+        {
+            _spriteBatch = new SpriteBatch(GraphicsDevice);
+
+            // TODO: use this.Content to load your game content here
+        }
+
+        protected override void Update(GameTime gameTime)
+        {
+            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
+                Exit();
+
+            // Make sure each entity moves around the screen
+            foreach (IEntity entity in _entities)
+            {
+                entity.Update(gameTime);
+            }
+
+            // Make sure all collisions are detected and the OnCollision event for each is called
+            _collisionComponent.Update(gameTime);
+
+            base.Update(gameTime);
+        }
+
+        protected override void Draw(GameTime gameTime)
+        {
+            GraphicsDevice.Clear(Color.CornflowerBlue);
+
+            // Draw all the entities
+            _spriteBatch.Begin();
+            foreach (IEntity entity in _entities)
+            {
+                entity.Draw(_spriteBatch);
+            }
+
+            _spriteBatch.End();
+
+            base.Draw(gameTime);
+        }
+    }
+}

+ 16 - 0
src/DocumentationSamples/Collision/Collision/IEntity.cs

@@ -0,0 +1,16 @@
+// Copyright (c) Craftwork Games. All rights reserved.
+// Licensed under the MIT license.
+// See LICENSE file in the project root for full license information.
+
+using Microsoft.Xna.Framework.Graphics;
+using Microsoft.Xna.Framework;
+using MonoGame.Extended.Collisions;
+
+namespace Collision
+{
+    public interface IEntity : ICollisionActor
+    {
+        public void Update(GameTime gameTime);
+        public void Draw(SpriteBatch spriteBatch);
+    }
+}

BIN
src/DocumentationSamples/Collision/Collision/Icon.bmp


BIN
src/DocumentationSamples/Collision/Collision/Icon.ico


+ 6 - 0
src/DocumentationSamples/Collision/Collision/Program.cs

@@ -0,0 +1,6 @@
+// Copyright (c) Craftwork Games. All rights reserved.
+// Licensed under the MIT license.
+// See LICENSE file in the project root for full license information.
+
+using var game = new Collision.Game1();
+game.Run();

+ 43 - 0
src/DocumentationSamples/Collision/Collision/app.manifest

@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="utf-8"?>
+<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
+  <assemblyIdentity version="1.0.0.0" name="Collision"/>
+  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
+    <security>
+      <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
+        <requestedExecutionLevel  level="asInvoker" uiAccess="false" />
+      </requestedPrivileges>
+    </security>
+  </trustInfo>
+
+  <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
+    <application>
+      <!-- A list of the Windows versions that this application has been tested on and is
+           is designed to work with. Uncomment the appropriate elements and Windows will 
+           automatically selected the most compatible environment. -->
+
+      <!-- Windows Vista -->
+      <supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}" />
+
+      <!-- Windows 7 -->
+      <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />
+
+      <!-- Windows 8 -->
+      <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />
+
+      <!-- Windows 8.1 -->
+      <supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />
+
+      <!-- Windows 10 -->
+      <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
+
+    </application>
+  </compatibility>
+
+  <application xmlns="urn:schemas-microsoft-com:asm.v3">
+    <windowsSettings>
+      <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware>
+      <dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">permonitorv2,permonitor</dpiAwareness>
+    </windowsSettings>
+  </application>
+
+</assembly>