Quantcast
Channel: Community | MonoGame - Latest topics
Viewing all 6821 articles
Browse latest View live

Adding 3D Textures to Pipeline (Works, but Strange)

$
0
0

@autemox1 wrote:

This isn't so much a complaint but a 'am I even doing this right?' discussion of adding 3D models (with textures) to my project. Maybe it will help someone (such as myself in the future after I forget the process). I will walk step by step how I successfully load 3D models into my monogame project, including textures. The last 6 steps or so are where the strange stuff is.

Getting Set Up

Before we can bring your awesome textured 3D models into your MonoGame, you need to A. have a monogame program that can load .dae models and B. have a simple textured 3D model that you know works to test your program with.

Install Monogame

Install Windows Studio Community 2017 from visualstudio.com

Install Monogame 3.7.1 from monogame.net, this includes the Pipeline

Create Project

This method has been tested with MonoGame Windows 10 Universal (XAML) Project and MonoGame Windows Project and should work for all project types.

Fix 'Build Action' for Content/Content.mgcb

Build Action should point to Pipeline .exe file (E.G. C:\Program Files (x86)\MSBuild\MonoGame\v3.0\Tools\Pipeline.exe). Do this by right clicking Content/Content.mgcb in Solutions Explorer and selecting 'Open With…'

Create a test model from scratch

Before we can use models we downloaded from TurboSquid and other complex models, we should create a very simple model that we know works. Use this tutorial to do so: MonoGame Tutorial -- Creating and exporting a textured model from Blender to MonoGame

Create basic program to display your 3D Model

Create the basic program that displays your 3D model, including its textures. Use this tutorial to do so: MonoGame Tutorial Part Five: 3D Programming (text version: https://www.gamefromscratch.com/post/2015/08/20/Monogame-Tutorial-Beginning-3D-Programming.aspx) Test your program with the simple test model you made in the last step. You should now have a program with a simple rotating textured cube.

Adding Your Existing Models

Now comes the hard part. Getting your existing models with textures into Monogame is frustrating and fraught with problems related to converting to .dae and setting your texture's path.

Download Model

Download a cool model from www.turbosquid.com for Free. Preferrably one with existing textures and a filetype that can be open by Blender.

Convert your file to .dae with blender or other tools

Import your file to blender and export as a .dae file. In 3D View Enable Texture on Viewpoint Shading as in the picture and make sure your textures are showing correctly. If you are using older version of blender, make sure under 'Texture Options' you have UV Mapping enabled (newer versions do not ask).

Test .dae file to make sure it was converted successfully

Open the file with Autodesk FBX Converter and press 'Display Mode' until Display Mode is set to Textures. Your model and textures should be visible and looking as expected. If not, textures needs to be fixed in blender.

Open the .dae with a text editor and modify path

The .dae contains xml. Under library_images tag, there will be your path to your texture(s). Your new path should be set to something like this:

file://C:\Users\MyName\source\repos\Game1\Game1\Content\bin\WindowsStoreApp\MyTextureFilename.png

This path is determined by your project file and your pipeline. It is where your pipeline is saving it's .xnb files.

Add .png texture file to new path

Navigate to the long path above and add a .png or .jpg version of your texture. This is because when building your .dae file will want a .png or .jpg and will not build off a .xnb.

If there are already .xnb versions of your texture here, you may have to duplicate or rename them. At new path, change myTexture.xnb texture file name to myTexture_0.xnb. I'm not sure why adding _0 helps or if this has to be done everytime yet.

Run Pipeline Tool

Double click Content.mgcb in Solution Explorer to open pipeline tool.

Add .dae model and .png texture files

Add the .dae and .png resources to pipeline tool.

Change model importer to Fbx Importer in pipeline tool

Select your .dae in the pipeline tool and under properties change model importer to Fbx importer.

Build Pipeline Resources

Press Build in the pipeline.

Posts: 2

Participants: 2

Read full topic


SharpDXException (HRESULT: 0x80070057) when drawing mesh

$
0
0

@andrej wrote:

Hi everyone.

I've got simple Phong shader texturing model with noise. When I try to apply this shader to model, program crashes with exception:

System.InvalidOperationException: "An error occurred while preparing to draw. This is probably because the current vertex declaration does not include all the elements required by the current vertex shader. The current vertex declaration includes these elements: SV_Position0, NORMAL0."
Inner exception:
SharpDXException: HRESULT: [0x80070057], Module: [General], ApiCode: [E_INVALIDARG/Invalid Arguments], Message: The parameter is incorrect.

Stack trace:

   at Microsoft.Xna.Framework.Graphics.InputLayoutCache.GetOrCreate(VertexBufferBindings vertexBuffers)
   at Microsoft.Xna.Framework.Graphics.GraphicsDevice.PlatformApplyState(Boolean applyShaders)
   at Microsoft.Xna.Framework.Graphics.GraphicsDevice.ApplyState(Boolean applyShaders)
   at Microsoft.Xna.Framework.Graphics.GraphicsDevice.PlatformDrawIndexedPrimitives(PrimitiveType primitiveType, Int32 baseVertex, Int32 startIndex, Int32 primitiveCount)
   at Microsoft.Xna.Framework.Graphics.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType primitiveType, Int32 baseVertex, Int32 startIndex, Int32 primitiveCount)
   at Microsoft.Xna.Framework.Graphics.ModelMesh.Draw()
   at AS.Fractalyze.Core.FractalyzeGame.Draw(GameTime gameTime)
   at Microsoft.Xna.Framework.Game.DoDraw(GameTime gameTime)
   at Microsoft.Xna.Framework.Game.Tick()
   at Microsoft.Xna.Framework.UAPGameWindow.Tick()
   at Microsoft.Xna.Framework.UAPGamePlatform.<>c.<StartRunLoop>b__11_0(IAsyncAction action)

I have a couple of other shaders (just texturing, no Phong or noise stuff), they are applies ok.
Shader is built ok with pipeline tool; also I tested it in RenderMonkey (lol), it works ok.

What can cause this trouble?

Shader

Output code (little bit simplified)

Posts: 2

Participants: 2

Read full topic

Handling tile map coordinates in addition to world, camera, and screen coordinates

$
0
0

@MonoShane wrote:

I'm a little unsure as how to "best" handle tile coordinates when trying to implement a tiled map game.

Currently, I have the following 3 spaces set up:
- Screen space (game window)
- Camera space (not necessarily the same as screen space; I can put the camera anywhere within the game window, have virtual bounds, etc. I also have zoom and rotate working with my camera.)
- World space. The problem is that world space is 1:1 with pixels. So if I want to have 2 tiles that have a 32 pixel width next to each other, I have to specify that the tile gets drawn 32 world units adjacent. The same issue applies to game objects. To get a game object at tile coordinates <x, y>, I must scale it by the tile width (32 in this case).

Similarly, I can convert a point/Vector2 from any one of those spaces to another (e.g. mouse coordinates to world coordinates). So far, everything seems to be working great, even after putting the camera view in different spots of the game window and zooming and rotating. In the screenshot, we can see that the gargoyle is at 3,2 in tiled space (note that the tile map begins at <0, 0>, so it's 4 tiles to the right and 2 tiles down).

public static Point GetTilePositionForWorld(Vector2 worldPosition)
{
    return (worldPosition / 32).ToPoint();
}

One possible solution is, when creating game objects, to simply scale the position in the game object's class by the tile width. For example, in the constructor for creating a game object I could simply scale the position such that if I I create a new game object with a world position of, say, <5, 2> I can ensure the object gets drawn at <5, 2> in the tiled space. However, I am afraid this is not the right way. Ideally, I want to just specify any world coordinate <x, y> and ensure that it gets drawn in the corresponding <x, y> tile. That is, a 1:1 relationship between world and tile space.

Posts: 2

Participants: 2

Read full topic

SaveAsJpeg not Writing to the File

$
0
0

@Suicidal_Robot wrote:

I am creating a level editor for my game that exports an image file, with each pixel representing a specific tile. I am creating this map as a Texture2D using the SetData function. I can display this texture on the screen, but when I try to save it using the SaveAsJpeg function, I just get an empty file. I can export all of my sprite sheets that were imported from the content folder without issue. Is there something that I need to do to that Texture2D before I can export it? (I am creating my game using the UWP option).

This is how I am generating the Texture2D.

public void GenerateImage()
{
var colorData = new Color[30 * 17];
levelTex = new Texture2D(graphicsDevice, 30, 17);
for (int yPos = 0; yPos <= 29; yPos++)
{
for (int xPos = 0; xPos <= 16; xPos++)
{
colorData[(yPos * 17) + xPos] = new Color(100 + yPos, 200-xPos, 250);
}
}
levelTex.SetData(colorData,0, 30*17);
`

    }`

This is how I am generating the file.

public void ExportLevel()
        {
            string pathName = Windows.Storage.KnownFolders.SavedPictures.Path;

            try
            {
               System.IO.Directory.CreateDirectory(pathName + "/Hand Cannon Janky Reality Exported Levels");

               System.IO.Stream myFile = System.IO.File.Create(pathName + "/Hand Cannon Janky Reality Exported Levels/" + "FileName.png");
               levelTex.SaveAsJpeg(myFile, levelTex.Width, levelTex.Height);


           }
            catch (UnauthorizedAccessException exception)
            {
                System.Diagnostics.Debug.WriteLine("Cannot Save " + exception.Message);
            }

        }

Posts: 2

Participants: 2

Read full topic

Battling 3D Particle System

$
0
0

@LordAuric wrote:

Hey gang... New MonoGame dev here. I've managed to migrate my game over to MonoGame in no time. The only holdover is cleaning up the Particle System. I've read over several solutions with porting from XNA to MonoGame and implemented those solutions but I'm still running into issues. I'm changed my shorts to Vector2s and reordered my vertex declaration and everything compiles.

NOW here is one crazy part... if I swap NORMAL0 NORMAL1 assignments, I get some results but it's off (expected but odd that I get results swapping at all). The image below show the triangles rendering at an angle. They are not shifting to face the viewport as they did in XNA...

I'm sure it's something stupid I'm missing... Thoughts?

My vertex declaration:
` struct ParticleVertex {
// Stores the starting position of the particle.
public Vector3 Position;

    // Stores which corner of the particle quad this vertex represents.
    public Vector2 Corner;

    // Stores the starting velocity of the particle.
    public Vector3 Velocity;

    // Four random values, used to make each particle look slightly different.
    public Color Random;

    // The time (in seconds) at which this particle was created.
    public float Time;


    public static readonly VertexDeclaration VertexDeclaration = new VertexDeclaration
    (
      new VertexElement(0, VertexElementFormat.Vector3,
                             VertexElementUsage.Position, 0),
      new VertexElement(12, VertexElementFormat.Vector2,
                             VertexElementUsage.Normal, 0),
      new VertexElement(20, VertexElementFormat.Vector3,
                             VertexElementUsage.Normal, 1),
      new VertexElement(32, VertexElementFormat.Color,
                             VertexElementUsage.Color, 0),
      new VertexElement(36, VertexElementFormat.Single,
                             VertexElementUsage.TextureCoordinate, 0)
    );

    public const int SizeInBytes = 40;
}`

My shader code is here:
`
// Camera parameters.
float4x4 View;
float4x4 Projection;
float2 ViewportScale;

	// The current time, in seconds.
	float CurrentTime;

	// Parameters describing how the particles animate.
	float Duration;
	float DurationRandomness;
	float3 Gravity;
	float EndVelocity;
	float4 MinColor;
	float4 MaxColor;

	// These float2 parameters describe the min and max of a range.
	// The actual value is chosen differently for each particle,
	// interpolating between x and y by some random amount.
	float2 RotateSpeed;
	float2 StartSize;
	float2 EndSize;

	// Particle texture and sampler.
	texture Texture;

	sampler Sampler = sampler_state
	{
		Texture = (Texture);

		MinFilter = Linear;
		MagFilter = Linear;
		MipFilter = Point;

		AddressU = Clamp;
		AddressV = Clamp;
	};

	// Vertex shader input structure describes the start position and
	// velocity of the particle, and the time at which it was created,
	// along with some random values that affect its size and rotation.
	struct VertexShaderInput
	{
		float3 Position : SV_POSITION;
		float2 Corner : NORMAL0;
		float3 Velocity : NORMAL1;
		float4 Random : COLOR0;
		float Time : TEXCOORD0;
	};

	// Vertex shader output structure specifies the position and color of the particle.
	struct VertexShaderOutput
	{
		float4 Position : SV_POSITION;
		float4 Color : COLOR0;
		float2 TextureCoordinate : COLOR1;
	};

	// Vertex shader helper for computing the position of a particle.
	float4 ComputeParticlePosition(float3 position, float3 velocity,
		float age, float normalizedAge)
	{
		float startVelocity = length(velocity);

		// Work out how fast the particle should be moving at the end of its life,
		// by applying a constant scaling factor to its starting velocity.
		float endVelocity = startVelocity * EndVelocity;

		// Our particles have constant acceleration, so given a starting velocity
		// S and ending velocity E, at time T their velocity should be S + (E-S)*T.
		// The particle position is the sum of this velocity over the range 0 to T.
		// To compute the position directly, we must integrate the velocity
		// equation. Integrating S + (E-S)*T for T produces S*T + (E-S)*T*T/2.

		float velocityIntegral = startVelocity * normalizedAge +
			(endVelocity - startVelocity) * normalizedAge *
			normalizedAge / 2;

		position += normalize(velocity) * velocityIntegral * Duration;

		// Apply the gravitational force.
		position += Gravity * age * normalizedAge;

		// Apply the camera view and projection transforms.
		return mul(mul(float4(position, 1), View), Projection);
	}


	// Vertex shader helper for computing the size of a particle.
	float ComputeParticleSize(float randomValue, float normalizedAge)
	{
		// Apply a random factor to make each particle a slightly different size.
		float startSize = lerp(StartSize.x, StartSize.y, randomValue);
		float endSize = lerp(EndSize.x, EndSize.y, randomValue);

		// Compute the actual size based on the age of the particle.
		float size = lerp(startSize, endSize, normalizedAge);

		// Project the size into screen coordinates.
		return size * Projection._m11;
	}

	// Vertex shader helper for computing the color of a particle.
	float4 ComputeParticleColor(float4 projectedPosition,
		float randomValue, float normalizedAge)
	{
		// Apply a random factor to make each particle a slightly different color.
		float4 color = lerp(MinColor, MaxColor, randomValue);

		// Fade the alpha based on the age of the particle. This curve is hard coded
		// to make the particle fade in fairly quickly, then fade out more slowly:
		// plot x*(1-x)*(1-x) for x=0:1 in a graphing program if you want to see what
		// this looks like. The 6.7 scaling factor normalizes the curve so the alpha
		// will reach all the way up to fully solid.

		color.a *= normalizedAge * (1 - normalizedAge) * (1 - normalizedAge) * 6.7;

		return color;
	}

	// Vertex shader helper for computing the rotation of a particle.
	float2x2 ComputeParticleRotation(float randomValue, float age)
	{
		// Apply a random factor to make each particle rotate at a different speed.
		float rotateSpeed = lerp(RotateSpeed.x, RotateSpeed.y, randomValue);

		//float rotation = rotateSpeed * age;
		float rotation = 0;

		// Compute a 2x2 rotation matrix.
		float c = cos(rotation);
		float s = sin(rotation);

		return float2x2(c, -s, s, c);
	}

	// Custom vertex shader animates particles entirely on the GPU.
	VertexShaderOutput ParticleVertexShader(VertexShaderInput input)
	{
		VertexShaderOutput output;

		// Compute the age of the particle.
		float age = CurrentTime - input.Time;

		// Apply a random factor to make different particles age at different rates.
		age *= 1 + input.Random.x * DurationRandomness;

		// Normalize the age into the range zero to one.
		float normalizedAge = saturate(age / Duration);

		// Compute the particle position, size, color, and rotation.
		output.Position = ComputeParticlePosition(input.Position, input.Velocity,
			age, normalizedAge);

		float size = ComputeParticleSize(input.Random.y, normalizedAge);
		float2x2 rotation = ComputeParticleRotation(input.Random.w, age);

		output.Position.xy += mul(input.Corner, rotation) * size * ViewportScale;

		output.Color = ComputeParticleColor(output.Position, input.Random.z, normalizedAge);
		output.TextureCoordinate = (input.Corner + 1) / 2;

		return output;
	}

	// Pixel shader for drawing particles.
	float4 ParticlePixelShader(VertexShaderOutput input) : COLOR0
	{
		return tex2D(Sampler, input.TextureCoordinate) * input.Color;
	}

	// Effect technique for drawing particles.
	technique Particles
	{
		pass P0
		{
			VertexShader = compile vs_4_0_level_9_1 ParticleVertexShader();
			PixelShader = compile ps_4_0_level_9_1 ParticlePixelShader();
		}
	}

`

Posts: 4

Participants: 2

Read full topic

Maps Editor with auto-tileing

Problem with drawing part of Texture2D [HealthBar]

$
0
0

@Yorb_Yorbi wrote:

Hello,

I was trying to implement a HeathBar. I need two heathbars for two characters, and for 1st bar when I cut the health texture from Right to Left everything is working fine. But now I need to do the opposite, I need to cut a texture from Left to Right (image).

And I don't know how to do it properly.

It's my method where I calculate % of texture according to the current HP and then I set the sourceRectangle.
As I said for the right bar method is cutting from right to left and I don't know how to change it.

` public void Draw(SpriteBatch spriteBatch, double hp, bool isMonster, Vector2 cameraPos)
{
double healthIntoTexture = (hp * fullHealthInPixels) / (double)MaxHp;

        rectanglHealthLeft = new Rectangle(0, 0, (int)healthIntoTexture, healthTextureLeft.Height);
        rectanglHealthRight = new Rectangle(0, 0, (int)healthIntoTexture, healthTextureRight.Height); // ???????

        rectangleForBar = new Rectangle(0, 0, barTextureLeft.Width, barTextureLeft.Height);

        var originLeft = new Vector2(rectanglHealthLeft.Left, rectanglHealthLeft.Top);
        var originRight = new Vector2(rectanglHealthRight.Left, rectanglHealthRight.Top);

        var originBar = new Vector2(rectangleForBar.Left, rectangleForBar.Top);

        if (isMonster)
        {
            spriteBatch.Draw(barTextureLeft, new Vector2(cameraPos.X + 200 - 3, cameraPos.Y + 50 - 4), rectangleForBar, Color.White, 0.0f, originBar, 0.5f, SpriteEffects.None, 0.0f);
            spriteBatch.Draw(healthTextureLeft, new Vector2(cameraPos.X + 200, cameraPos.Y + 50), rectanglHealthLeft, Color.White, 0.0f, originLeft, 0.5f, SpriteEffects.None, 0.0f);
        }
        else
        {
            spriteBatch.Draw(barTextureRight, new Vector2(cameraPos.X + 1000 - 8, cameraPos.Y + 50 - 4), rectangleForBar, Color.White, 0.0f, originBar, 0.5f, SpriteEffects.None, 0.0f); 
            spriteBatch.Draw(healthTextureRight, new Vector2(cameraPos.X + 1000, cameraPos.Y + 50), rectanglHealthRight, Color.White, 0.0f, originRight, 0.5f, SpriteEffects.None, 0.0f); // ???
        }
    }`

Posts: 2

Participants: 1

Read full topic

AccessViolationException

$
0
0

@Cody_Stough wrote:

Hello, I've just recently started using MonoGame on my laptop and have had a greeat time with it. I decided to install it onto my Visual Studio on my desktop, but have been receiving an AccessViolationException thrown from Sharp3D.Direct11. After searching for a fix, ive seen that this has been a very common issue, but people seem to fix it where I cannot. I've already tried running VS as Admin. Most other discussion threads I see usually end up never finding a fix. I'm not sure if there is a category for issues like this, but if anyone is willing to enlighten me about this situation, I'm getting this error from a completely untouched project...

Posts: 1

Participants: 1

Read full topic


Matrix Forward's Y is inverted when the angle is >= 180 degrees

$
0
0

@Kimimaru wrote:

I'm a novice in low-level 3D and am working on a simple project to create a scene view camera similar to game engines like Godot, Unity, etc. I have all the angling correct and it looks great, but I'm encountering an issue with the Matrix's Forward vector that I can't wrap my head around.

If the camera is facing the world forward, the Forward vector returns a negative Y when angling the camera up and a positive Y when angling the camera down. However, when the camera is facing opposite the world forward, this is flipped. This causes my camera to move down when I move it forward despite it facing up and vice versa.

Here's how I'm creating my View matrix:

public Matrix ViewMatrix
{
    get
    {
        //Adding the position to the forward matrix causes it to not change the direction it's facing when translating
        Vector3 lookForward = Vector3.Forward + position;
        
        //Create a look at Matrix
        //To account for rotation, create a rotation about the Y with the y angle and an X with the x angle
        viewMatrix = Matrix.CreateLookAt(position, lookForward, Vector3.Up)
            * Matrix.CreateRotationY(yAngle)
            * Matrix.CreateRotationX(xAngle);

        return viewMatrix;
    }
}

This looks okay to me because the view appears fine, but I feel something is off due to how it works with my controls. Here's my code for controlling the camera:

public void Update(GameTime gameTime)
{
    MouseState state = Mouse.GetState(gameWindow);
    KeyboardState kstate = Keyboard.GetState();

    if (kstate.IsKeyDown(Keys.W))
    {
        Vector3 forward = viewMatrix.Forward;
        forward.Z = -forward.Z;
        position -= (forward * unitsPerSecond) * (float)gameTime.ElapsedGameTime.TotalSeconds;
    }
    else if (kstate.IsKeyDown(Keys.S) == true)
    {
        Vector3 forward = viewMatrix.Forward;
        forward.Z = -forward.Z;
        position += (forward * unitsPerSecond) * (float)gameTime.ElapsedGameTime.TotalSeconds;
    }
    if (kstate.IsKeyDown(Keys.A) == true)
    {
        Vector3 right = viewMatrix.Right;
        right.Z = -right.Z;
        right.Y = 0f;
        position -= (right * unitsPerSecond) * (float)gameTime.ElapsedGameTime.TotalSeconds;
    }
    else if (kstate.IsKeyDown(Keys.D) == true)
    {
        Vector3 right = viewMatrix.Right;
        right.Z = -right.Z;
        right.Y = 0f;
        position += (right * unitsPerSecond) * (float)gameTime.ElapsedGameTime.TotalSeconds;
    }
    if (kstate.IsKeyDown(Keys.Q) == true)
    {
        position.Y -= (unitsPerSecond) * (float)gameTime.ElapsedGameTime.TotalSeconds;
    }
    else if (kstate.IsKeyDown(Keys.E) == true)
    {
        position.Y += (unitsPerSecond) * (float)gameTime.ElapsedGameTime.TotalSeconds;
    }

    if (state.RightButton == ButtonState.Pressed)
    {
        if (Angling == false)
        {
            Angling = true;
        }
        else
        {
            Vector2 diff = state.Position.ToVector2() - mState.Position.ToVector2();

            yAngle += (diff.X * anglesPerSecond) * (float)gameTime.ElapsedGameTime.TotalSeconds;
            xAngle += (diff.Y * anglesPerSecond) * (float)gameTime.ElapsedGameTime.TotalSeconds;
        }
    }
    else
    {
        Angling = false;
    }

    mState = state;
    kbState = kstate;
}

I think the Y is inverting due to the X rotation, but I'm not 100% sure on this. Is there something that stands out that I'm doing wrong?

Posts: 3

Participants: 2

Read full topic

GamePad index becomes incorrect after disconnecting another GamePad whose index was lower (and was connected first)

$
0
0

@Rafael_Zacharias wrote:

Hi everyone!

I'm new to this forum. My name is Rafael and I've been using MonoGame for the last 6 months.
I've recently decided to create a 2D engine and I'm on the InputManager part where I manage gamePads connected and assign them to player slots.

While testing my engine, I came up with something strange that I don't know exactly if anyone else had experienced it before. I am using Windows 10 and the OpenGL cross platform project of MonoGame 3.7, also, to test I am using two identical XboxOne controllers via USB.

The steps to reproduce this issue are very easy:

  1. Connect gamePad A, monogame will assign it to index 0.
  2. Connect gamePad B, monogame will assign it to index 1.
  3. If you disconnect gamePad A (the one at index 0), you will notice that monogame still remembers correctly that gamePad B is at index 1, but upon connecting gamePad A again, it is not assigned to any slot, and gamePad B becomes both index 1 (as it was) and now also index 0.

Ideal behavior: It should be expected that upon connecting a gamePad, it either gets the first empty slot (in that case index 0 because it was free), or add one to the highest index being used (in that case, would be assigned to index 2). What baffles me not even the fact that the newly connected controller didn't had an index assigned to it, but that the controller that remained connected (index 1, gamePad B), gets to have index 0 too as soon as the new gamePad is connected.

Remarks: This issue does not happen if its the other way around. For example, if you have a gamePad connected as slot 0, and connect another one at slot 1, and disconnect and connect again the slot 1 controller as many times as you need, the slot 1 will always be assigned to slot 1, and the previous controller will always stay at slot 0 (as expected).

What would be a possible solution to this issue?

Thanks!!

Summary: It a gamePad with a LOWER index is disconnected and connected again while another gamePad with a HIGHER index exists, the newly connected gamePad does not have an index assigned to it, and the gamePad with HIGHER index respondes to both index 0 and 1.

Posts: 1

Participants: 1

Read full topic

VS and game freeze when hitting breakpoint

$
0
0

@Zcion wrote:

I am running VS 2017 on Win10 with Monogame 3.7.

I can use break points fine almost anywhere in my game except in a particular piece of code where if I am using a breakpoint both VS and the game window hang and I need to kill the game process to get VS to respond again. Anywhere else is fine.

This is in one of my scene's update loop

public override void Update(GameTime gameTime)
	{
		if (mouseInputManager.LeftButtonReleased)
		{
			PathFinder pathfinder = new PathFinder(pathFindingWeightedGraph);
			IPathFindingLocation target = pathFindingWeightedGraph.GetPathFindingLocationAtScenePosition(mouseInputManager.Position);
				//Camera.GetSceneRelativePositionFromCameraRelativePosition(mouseInputManager.Position));

			IPathFindingLocation start = pathFindingWeightedGraph.GetPathFindingLocationAtScenePosition(
				((TransformComponent)EntityManager.GetComponentForEntity("prototypeCrewMember", "Transform")).SceneRelativePosition);

			Debug.WriteLine("Target : " + target.ScenePosition);
			Debug.WriteLine("Start : " + start.ScenePosition);
			
			generalDebugUIWidget.AddColorBlockToDraw(target.ScenePosition, new Vector2(15, 15), Color.Black);
			generalDebugUIWidget.AddColorBlockToDraw(start.ScenePosition, new Vector2(15, 15), Color.Black);


		}

		base.Update(gameTime);
	}

If I put a breakpoint anywhere in the if statement I have the problem as soon as the if returns true (when I click somewhere in the game screen).

Anyone has an idea what could be happening ?

Posts: 3

Participants: 2

Read full topic

How can I view this SDL2.dll source?

$
0
0

@LCEngine wrote:

I want to change some of the code in sdl2.dll. But I don't know where this source code is. Does anyone know where the monogame dependency library sdl source is?

The official explanation is:

If the application draws the composition window, the default IME window does not have to show its composition window. In this case, the application must clear the ISC_SHOWUICOMPOSITIONWINDOW value from the lParam parameter before passing the message to DefWindowProc or ImmIsUIMessage. To display a certain user interface window, an application should remove the corresponding value so that the IME will not display it.

//case WM_IME_SETCONTEXT:
//    *lParam = 0;
//    break;

Posts: 1

Participants: 1

Read full topic

Loading IntermediateSerializer XML Via Content Pipeline?

$
0
0

@tsukito wrote:

Hello everyone,

I came across the IntermediateSerializer, it looked perfect for my map-loading purposes, and so I used it to serialize some dummy info. Now, I have a test map XML file that looks like this :

<?xml version="1.0" encoding="utf-8"?>
<XnaContent xmlns:TileSystem="PlatformerPrototype.TileSystem" xmlns:PlatformerPrototype="PlatformerPrototype">
  <Asset Type="TileSystem:TileMap">
    <width>20</width>
    <height>15</height>
    <tileSetImage>
      <Name>Sprites\player</Name>
      <Tag Null="true" />
    </tileSetImage>
    <tileWidth>32</tileWidth>
    <tileHeight>32</tileHeight>
    <tileLayers>
      <Item>0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0</Item>
    </tileLayers>
    <gameObjects>
      <Item Type="PlatformerPrototype:Solid">
        <position>0 300</position>
        <maskPosition>0 0</maskPosition>
        <maskSize>640 180</maskSize>
        <depth>0</depth>
        <debugTexture>
          <Name>Sprites\player</Name>
          <Tag Null="true" />
        </debugTexture>
      </Item>
      <Item Type="PlatformerPrototype:Solid">
        <position>0 100</position>
        <maskPosition>0 0</maskPosition>
        <maskSize>300 140</maskSize>
        <depth>0</depth>
        <debugTexture>
          <Name>Sprites\player</Name>
          <Tag Null="true" />
        </debugTexture>
      </Item>
    </gameObjects>
  </Asset>
</XnaContent>

Ok, so now, where do I go?

For now, I only have one project with everything in it.
Apparently, I'm supposed to create a new "class library" project and add it to the references.
The thing is, I'm new to C# in general and don't know how to do that.

What should I put in my second project?
What should I put in my main project?

I'm using Visual Studio 2017 if that helps in providing some guidance as to what I have to do?
I'm sorry for the stupid question, but I'm genuinely puzzled.

Thank you in advance,

Posts: 1

Participants: 1

Read full topic

[SOLVED] Crash when setting a hardware mouse cursor from a sprite... any ideas?

$
0
0

@Roxfall wrote:

{"Failed to set surface for mouse cursor: CreateIconIndirect(): The parameter is incorrect.\r\n"} System.InvalidOperationException

Stack Trace:
StackTrace " at Microsoft.Xna.Framework.Input.MouseCursor.PlatformFromTexture2D(Texture2D texture, Int32 originx, Int32 originy)\r\n" string

So I was messing around with Mouse.SetCursor(MouseCursor.FromTexture2D(sprite, 0, 0));

And by messing around I mean setting it several times per second (i.e. every frame). Windows 10, VS 2017.

This crash pops out after maybe half a minute of incessant clicking, but is 100% reproducible under those conditions.

Has anyone seen this before? Google has failed me.

I'd appreciate any pointers on how to prevent this crash.

It seems that I can avoid it by setting mouse cursor sprite less frequently, but that means I can't have an animated mouse cursor. Even then, that's not a guarantee if there's a bug somewhere in the pipeline.

Should I just put this inside a giant try{} block and forget about it?

Thanks for reading!

Posts: 7

Participants: 4

Read full topic

SpaceWorms Release and Key Giveaway

$
0
0

@mgulde wrote:

Dear amazing MonoGame Community,

We have just published our first title SpaceWorms on Steam.

It's a pretty dark but humorous artillery game blended with a turn-based strategic builder: You take on the role of "Ze Wormperor" and must conquer the known (and pretty flat) universe by destroying, stealing from, colonizing, and conquering the surrounding planets and your enemies.

This release would have not been so possible without your support. Thank you.

As a return favor for your time invested in answering our countless questions, please use one of the below 49 Steam keys to get immediate access to SpaceWorms (maybe it's a good idea to comment on which keys are already in use).

  1. 9I2F3-KDC94-847LV
  2. Q9QKP-Y8GIW-WMEPY
  3. K0CL6-EH8Y6-L0QFE
  4. 40D55-4XMIV-F9C3N
  5. NPM5N-063TH-0XQ3X
  6. L4K73-F09EW-CCR98
  7. 2AC3Q-62V66-RFXRI
  8. N3WTI-K3DM9-XTKQ4
  9. XY5Q8-4YKZN-AIBAA
  10. ZAV2A-99RF3-TBJ68
  11. C2RNN-3TAHM-JAGBP
  12. XN2J9-0DT9Z-6Y3H5
  13. QK3IL-ZK4WG-ZK8NP
  14. JVHQR-04L8F-KW220
  15. ADKBW-2RV4H-DAY9X
  16. YICPD-NPT5V-494A3
  17. BDHYA-6MBL2-RF2JK
  18. C0EWD-HNHL3-K325R
  19. T77HR-I58VB-JLE42
  20. NQV4V-3ZPVJ-P4W4Y
  21. NAYAK-QXGH7-8FTW5
  22. 8572P-NEPTG-B9BNK
  23. PKT0V-TRX3G-JAY8V
  24. VPFEV-E2EIW-Q84AD
  25. VNDXM-YVR60-IE96W
  26. 5Q60Q-LCQ75-EEGF0
  27. 38LZ0-095C6-8Z9V5
  28. 3CFF7-CBYX5-TRGHF
  29. YYPA2-LZD8J-GN07I
  30. V633Z-DA9VK-45HJH
  31. TQ20J-AZR4T-FNXEJ
  32. 5YG3P-AHLLV-95R5F
  33. NEZFC-4Z28Q-NKYV4
  34. NER82-Q4KVM-RQXTN
  35. ZXVFY-MANNA-AW9T0
  36. 5GII8-0Y2LN-HBHY2
  37. 8GVX3-8X7W5-3LZKF
  38. GBHRX-PXG3L-85WMW
  39. K8W4T-H09M2-3VQKD
  40. 89WX2-3W75Z-TJPC4
  41. 55ZJ6-BZM8V-6G7H6
  42. 2E3BP-B0ALT-5X9MW
  43. AA0PD-7GRBW-4PWTV
  44. ITW59-9Q8LE-Q5HTY
  45. ZAVGZ-3N9ZP-QJX54
  46. 9D06X-CWT00-P089H
  47. MV68H-2KX0H-V9KEF
  48. 7FPBL-ZE9P2-22BY6
  49. BT8FX-DMCIW-HHE97

Best wishes
- Max aka. His Wormnificence

Posts: 1

Participants: 1

Read full topic


RayTracing Collision Detection For 2d tile games

$
0
0

@Mattlekim wrote:

Hello every one as you will know collision detection can be a real pain the backside.

Iv recently gone back to a old project. Its a 2d grid based platformer. Anyhow the collision detection is a messy hack, Stuff added for what happens if you collide with a tile on x and y at same time, what happens when your object is traveling super fast plus other hacks.

Anyhow a few years ago I implemented this fast tray trace for my Minecraft cone test. the paper is here http://www.cse.yorku.ca/~amana/research/grid.pdf

Well I thought that would be good if I could implment a good collisoin detection based on this. Iv tryed before and not got it perfect, but I think this time I have. Its been a pain to get working but iv made it very flexible so it will fit just about anyone's projects with very little code

It has the following benifits.
1: its fast
2: super fast object do not tunnel or skip tiles.
3: its very accurate

Here is a video of it working https://youtu.be/qn-WMqO9tR4
the projectile is moving at more than 40 pixels per update. and the tile width is 20 pixels.

Bellow is the code for thouse who are interested. Its very late now so tommorow ill zip and upload the project

Hope its of some use to someone. Your comments always welcome.

using Microsoft.Xna.Framework;
namespace Riddlersoft.Core.Collisions
{
    public enum CollisionDirection
    {
        Horizontal,
        Vertical,
    }

    public struct Collision
    {
        public Point GridLocation { get; internal set; }
        public Coordinate ObjectCoordinate { get; internal set; }
        public CollisionDirection Direction { get; internal set; }
        public object Tile { get; internal set; }
        public object Grid { get; internal set; }
    }
}

using Microsoft.Xna.Framework;

namespace Riddlersoft.Core.Collisions
{
    /// <summary>
    /// this structur contains both a position and velocity for an 2d game object
    /// </summary>
    public struct Coordinate
    {
        /// <summary>
        /// the position of the object
        /// </summary>
        public Vector2 Position;
        /// <summary>
        /// the velocity of the object
        /// </summary>
        public Vector2 Velocity;

        /// <summary>
        /// creates a new coordinate instance
        /// </summary>
        /// <param name="position">the start position of the object</param>
        /// <param name="velocity">the start velocity of the object</param>
        public Coordinate(Vector2 position, Vector2 velocity)
        {
            Position = position;
            Velocity = velocity;
        }
    }
}

using System;
using Microsoft.Xna.Framework;

namespace Riddlersoft.Core.Collisions
{
    public class RayCollisionDetector
    {
        /// <summary>
        /// the cell or tile size
        /// </summary>
        private int _cellSize;

        /// <summary>
        /// the amount of bounce we want after a collisoin
        /// 0 is no bound 1 is perfect bounce
        /// </summary>
        private float _amountOfBounce = 1;
        public float AmountOfBounce
        {
            get
            {
                return _amountOfBounce;
            }
            set
            {
                _amountOfBounce = MathHelper.Clamp(value, 0, 1);
            }
        }

        /// <summary>
        /// the size of the grid you want to do collision check on
        /// usual the total size of the grid
        /// </summary>
        private Rectangle _gridBounds;

        /// <summary>
        /// this function fires as soon as an object enters the cell
        /// return false to ignore collision of tile ie air
        /// return true to enable the collision
        /// OnCellEnter(CollisionDirection dir, Point gridLocation, Object sender);
        /// </summary>
        public Func<CollisionDirection, Point, object, bool> OnCellEnter;

        /// <summary>
        /// this action fires for prossesing the collision with the cell
        /// ProssesCellColision(Collision col);
        /// </summary>
        public Action<Collision> ProssesCellColision;

        /// <summary>
        /// creates a new instace of the collision detector
        /// </summary>
        /// <param name="cellSize">the size in pixels of each cell</param>
        /// <param name="gridBounds">the size of the 2d array</param>
        public RayCollisionDetector(int cellSize, Rectangle gridBounds)
        {
            _cellSize = cellSize;
            _gridBounds = gridBounds;
        }


        private float CalculateDistance(float pos, float vel)
        {
            if (vel > 0)
                return (float)Math.Ceiling(pos / _cellSize) * _cellSize - pos;

            return pos - (float)Math.Floor(pos / _cellSize) * _cellSize;
        }

        private float CalculateTravelTime(float distance, float vel)
        {
            if (vel == 0)
                return float.PositiveInfinity;

            return distance / Math.Abs(vel);
        }

        private bool ValidateHorizontalColision<T>(Point p, Vector2 vel, float travelTime, T[,] grid)
        {
            if (travelTime > 1) //if no collision
                return false;

            int dir = Math.Sign(vel.X);
            Point tile = new Point(p.X + dir, p.Y);

            if (tile.X <= _gridBounds.X || tile.X >= _gridBounds.Width)
                return true;

            if (OnCellEnter != null)
                return OnCellEnter(CollisionDirection.Horizontal, tile, grid[tile.X, tile.Y]);
            
           // if (grid[p.X + dir, p.Y]) //if we can walk here there is not a collision
                //return false;

            //   if (grid[p.X, p.Y]) //if this side block is passible we have a collision
            //  return true;
            return true;
        }

        private bool ValidateVerticalColision<T>(Point p, Vector2 vel, float travelTime, T[,] grid)
        {
            if (travelTime > 1) //if no collision
                return false;

            int dir = Math.Sign(vel.Y);
            Point tile = new Point(p.X, p.Y + dir);

            if (tile.Y <= _gridBounds.Y || tile.Y >= _gridBounds.Height)
                return true;

            if (OnCellEnter != null)
                return OnCellEnter(CollisionDirection.Horizontal, tile, grid[tile.X, tile.Y]);

            //  if (grid[p.X, p.Y + dir]) //if we can walk here there is not a collision
            // return false;

            //    if (grid[p.X, p.Y]) //if this side block is passible we have a collision
            //   return true;
            return true;
        }

        /// <summary>
        /// Handle colision for one update cycle
        /// </summary>
        /// <typeparam name="T">the tile type in your 2d array</typeparam>
        /// <param name="pos">the position of the object you want to check a colision with</param>
        /// <param name="vel">the velocity of the object you want to check a colision with</param>
        /// <param name="grid">the 2d array that represents you gameing grid</param>
        /// <returns>by default the collision detector will invert the velocity after a collision and also set the position.
        /// You can then set ether the pos and vel return to your object or you can handle it on your own
        /// </returns>
        public Coordinate HandleColision<T>(Vector2 pos, Vector2 vel, T[,] grid)
        {
           
            Vector2 preColVel = vel;
            //first calculate distance to next cell
            Vector2 distance = new Vector2(CalculateDistance(pos.X, vel.X),
                CalculateDistance(pos.Y, vel.Y));

            //now calculate travel time
            Vector2 travelTime = new Vector2(CalculateTravelTime(distance.X, vel.X),
                CalculateTravelTime(distance.Y, vel.Y));

            Vector2 blockTraveTime = new Vector2(_cellSize / Math.Abs(vel.X), _cellSize / Math.Abs(vel.Y));
            Point gridLocation = new Point((int)Math.Floor(pos.X / _cellSize), (int)Math.Floor(pos.Y / _cellSize));
            while (travelTime.X <= 1 || travelTime.Y <= 1)
            {
                bool HorCol = false, VerCol = false;

                if (travelTime.X < travelTime.Y)
                {
                    HorCol = ValidateHorizontalColision(gridLocation, vel, travelTime.X, grid);
                    if (!HorCol)
                    {
                        // deltaTraveTime += blockTraveTime;
                        travelTime.X += blockTraveTime.X;
                        //    if (deltaTraveTime.Y > deltaTraveTime.X)
                        gridLocation.X += Math.Sign(vel.X);
                        continue;
                    }
                }
                else
                {
                    VerCol = ValidateVerticalColision(gridLocation, vel, travelTime.Y, grid);
                    if (!VerCol)
                    {
                        //deltaTraveTime += blockTraveTime;
                        travelTime.Y += blockTraveTime.Y;
                        //  if (deltaTraveTime.Y < deltaTraveTime.X)
                        gridLocation.Y += Math.Sign(vel.Y);
                        continue;
                    }
                }

                if (HorCol) //logic for horizontal collision
                {
                    gridLocation.X += Math.Sign(vel.X);
                    if (ProssesCellColision != null) //if user has collision responce
                    {
                        Collision col = new Collisions.Collision()
                        {
                            Direction = CollisionDirection.Horizontal,
                            GridLocation = gridLocation,
                            ObjectCoordinate = new Coordinate(pos, vel),
                            Tile = grid[gridLocation.X, gridLocation.Y],
                            Grid = grid,
                        };
                        ProssesCellColision(col);

                    }
                    preColVel = vel * travelTime.X;
                    pos.X -= Math.Sign(vel.X); //take away 1 pixel so that we are not in the block
                    //this is requied otherwise we will get posistion errors

                    vel.X *= -_amountOfBounce;
                    break;
                }

                if (VerCol) //logic for vertical collisoins
                {
                    gridLocation.Y += Math.Sign(vel.Y);
                    if (ProssesCellColision != null) //if user has collision responce
                    {
                        Collision col = new Collisions.Collision()
                        {
                            Direction = CollisionDirection.Vertical,
                            GridLocation = gridLocation,
                            ObjectCoordinate = new Coordinate(pos, vel),
                            Tile = grid[gridLocation.X, gridLocation.Y],
                            Grid = grid,
                        };
                        ProssesCellColision(col);
                    }

                    preColVel = vel * travelTime.Y;
                    pos.Y -= Math.Sign(vel.Y); //take away 1 pixel so that we are not in the block
                    //this is requied otherwise we will get posistion errors

                    vel.Y *= -_amountOfBounce;
                    break;
                }

            }
            pos.X += preColVel.X;
            pos.Y += preColVel.Y;

            return new Collisions.Coordinate(pos, vel);
        }
    }
}

finaly test program

using Microsoft.Xna.Framework;
using Riddlersoft.Core.Collisions;

namespace GridRayTrace
{
    public class Mob
    {
        public Vector2 Pos, Vel;

        RayCollisionDetector _rcd;
        float gravity = .08f;
        public Mob(Vector2 _pos, Vector2 _vel,bool[,] grid)
        {
            Pos = _pos;
            Vel = _vel;
            grid[(int)(Pos.X / 20), (int)(Pos.Y / 20)] = false; //make start tile empty space
            _rcd = new RayCollisionDetector(20, new Rectangle(0, 0, 500, 500));
            _rcd.OnCellEnter = OnCellCollision;
            _rcd.ProssesCellColision = OnCollision;
            _rcd.AmountOfBounce = .95f;
        }

        private void OnCollision(Collision col)
        {
         //   if (col.Direction == CollisionDirection.Horizontal )
            //    Vel.X *= -1;
           // else
             //   Vel.Y *= -1;

            bool[,] grid = col.Grid as bool[,];
            grid[col.GridLocation.X, col.GridLocation.Y] = false;
        }

        private bool OnCellCollision(CollisionDirection dir, Point gridLocation, object sender)
        {
            bool b = (bool)sender;
            if (b)
                return true;

            return false;
        }


        public void Update(float dt, bool[,] grid)
        {
           // Vel.Y += gravity;
            Coordinate newLoc = _rcd.HandleColision<bool>(Pos, Vel, grid);
            Pos = newLoc.Position;
            Vel = newLoc.Velocity;
        }
    }
}

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

using System;
namespace GridRayTrace
{

    public class Game1 : Game
    {
        private bool[,] _grid = new bool[50, 50];

        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        private Texture2D tex;

        Mob mob;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            this.graphics.PreferredBackBufferWidth = 1000;
            this.graphics.PreferredBackBufferHeight = 1000;
        }

       
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            
            for (int x = 0; x < 50; x++)
                for (int y = 0; y < 50; y++)
                {
                    _grid[x, y] = true;
                }

            mob = new GridRayTrace.Mob(new Vector2(304.5f, 204.3f), new Vector2(23f, 40f), _grid);
            base.Initialize();
        }

        
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            tex = new Texture2D(GraphicsDevice, 1, 1);
            tex.SetData<Color>(new Color[1] { Color.White });
            // TODO: use this.Content to load your game content here
        }

        
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        protected override void Update(GameTime gameTime)
        {
            float dt = (float)gameTime.ElapsedGameTime.TotalSeconds;

                mob.Update(dt, _grid);
            // TODO: Add your update logic here
            base.Update(gameTime);
        }


        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            spriteBatch.Begin();

            //draw grid
            for (int x = 0; x < 50; x++)
                for (int y = 0; y < 50; y++)
                {
                    if (!_grid[x, y])
                        spriteBatch.Draw(tex, new Rectangle(x * 20, y * 20, 20, 20), Color.White);
                    else
                        spriteBatch.Draw(tex, new Rectangle(x * 20, y * 20, 20, 20), Color.LightGreen);
                }

            for (int x = 0; x < 50; x++)
                spriteBatch.Draw(tex, new Rectangle(x * 20, 0, 1, 1000), Color.Black);

            for (int y = 0; y < 50; y++)
                spriteBatch.Draw(tex, new Rectangle(0, y * 20, 1000, 1), Color.Black);

            Vector2 dir = mob.Vel;
            dir.Normalize();
            for (int i = 1; i < 10; i++)
                spriteBatch.Draw(tex, new Rectangle(Convert.ToInt32(mob.Pos.X - 1 - dir.X * i),
                    Convert.ToInt32(mob.Pos.Y - 1 - dir.Y * i), 3, 3), Color.Blue);
            spriteBatch.Draw(tex, new Rectangle(Convert.ToInt32(mob.Pos.X - 1), Convert.ToInt32(mob.Pos.Y - 1), 3, 3), Color.Red);

            spriteBatch.Draw(tex, new Rectangle(Convert.ToInt32(mob.Pos.X - 1 + mob.Vel.X), Convert.ToInt32(mob.Pos.Y - 1 + mob.Vel.Y), 3, 3), Color.LightPink);
            spriteBatch.End();
            // TODO: Add your drawing code here

            base.Draw(gameTime);
        }
    }
}

Posts: 1

Participants: 1

Read full topic

Need guidance regarding merging classes together

$
0
0

@Neonovion wrote:

Hello everyone! I'm new to game development in general, and especially XNA/MonoGame(excited to learn more!)
I'm hoping the community can help me figure out this problem I'm having.

I'll preface this by saying this is a hobby project. I have followed along with the "Neon Shooter" tutorial series: Tutorial Series

I've gotten to the point where I've "completed" the game essentially. So now I'm stuck trying to implement a very crucial part of any game... menus! For this project I'd like to use the standard Game State Management sample, which someone has so kindly ported to MonoGame: Game State Management Port (works perfectly by the way, even in UWP!)

When I attempt to merge GameRoot/Game1 into GameplayScreen however, I constantly run into issues, especially ones regarding the LoadContent method (GraphicsDevice is the most common conflict)

Looking at other people using the sample for their projects on GitHub gives me an okay general idea on its usage, but I still come up empty-handed with a broken mess by the end of the "merge". For example: Leaving core components that should be left in GameRoot, then moving over everything else (LoadContent, Update, Draw, etc.)

So ultimately, I'm stuck with how I should go about merging the two together. Menu to Game, Game to Menu, etc.

If anyone can graciously guide me on how one might go about merging/divvying Game1/GameRoot into GameplayScreen, that would be SO greatly appreciated! (as I've been scratching my head trying to figure this out for over a week now!)

Thank you!

Posts: 2

Participants: 2

Read full topic

Error when building from source due to CollectContentReferences task

$
0
0

@kgambill wrote:

I've recently installed MonoGame and have begun building our first game project using it. Initially I installed the prebuilt MonoGame install and everything worked fine with a simple Game1 project using the MonoGame Framework.

Currently I'm in the process of attempting to change our project over to include our game project as well as all the source for the MonoGame Framework (for Windows). I'm attempting to get things set up so that there are no dependencies on other programmers installing the MonoGame SDK on their own, everything is built and linked directly from the source depot.

For reference, a rough idea of our directory structure is:
/code/external/MonoGame-3.7.1
/code/src/Game1.csproj

The external/MonoGame-3.7.1 directory has the downloaded source from GitHub and I've run protobuild on it already.

The first issue I encountered was the Game1.csproj file had the following:

I updated this to be:

That solved the issue, but now when attempting to build I'm seeing the following error:
1>\code\external\MonoGame-3.7.1\MonoGame.Framework.Content.Pipeline\MonoGame.Content.Builder.targets(40,5): error MSB4062: The "MonoGame.Build.Tasks.CollectContentReferences" task could not be loaded from the assembly \code\external\MonoGame-3.7.1\MonoGame.Framework.Content.Pipeline\MonoGame.Build.Tasks.dll. Could not load file or assembly 'file:///\code\external\MonoGame-3.7.1\MonoGame.Framework.Content.Pipeline\MonoGame.Build.Tasks.dll' or one of its dependencies. The system cannot find the file specified. Confirm that the declaration is correct, that the assembly and all its dependencies are available, and that the task contains a public class that implements Microsoft.Build.Framework.ITask.

The issue is that the DLL is not in that location, it's in
code\external\MonoGame-3.7.1\Tools\MonoGame.Build.Tasks\bin\Windows\AnyCPU\Debug

However I'm not sure what the proper solution is here. I could just update the Output Directory of the BuildTasks project to point to where the ContentReferences error is mentioning, but I suspect that is a band-aid instead of a proper fix as I'm not sure exactly where that path is being determined in the first place. I'm not extremely familiar with the .targets file.

Any advice on this (and setting up the source to be fully built from within your game's solution) is greatly appreciated.

Posts: 1

Participants: 1

Read full topic

This MGFX effect is for an older release of MonoGame and needs to be rebuilt.

$
0
0

@Peon501 wrote:

Infinitespace Studios Remote Effect Processor effect files are outdated.
This MGFX effect is for an older release of MonoGame and needs to be rebuilt.
Can anyone host a new Effect Processor soo we Linux users could use it :)?

Posts: 1

Participants: 1

Read full topic

[Solved] Compiled Content does not end up in game directory

$
0
0

@oblivion165 wrote:

Hello,

I recently started having the issue where the Content Manager doesn't copy the files to the game directory. They build without error and they are in the content folder but never get copied to the game directory.

Any ideas?

----------------------------- Global Properties ----------------------------

/outputDir:bin/$(Platform)
/intermediateDir:obj/$(Platform)
/platform:Windows
/config:
/profile:Reach
/compress:False

Posts: 5

Participants: 2

Read full topic

Viewing all 6821 articles
Browse latest View live