Quantcast
Channel: Community | MonoGame - Latest topics

Building/debugging for Android on macOS with VS Code

$
0
0

I’m looking for a way to build/debug for Android while using macOS and VS Code for development.

I’ve looked at this , but I am not using Visual Studio for Mac, just VS Code and .NET CLI.

Also, is there any documentation about how Monogame handles different screen sizes?

1 post - 1 participant

Read full topic


Trouble with Windows Compatibility: App Crashes on Startup

$
0
0

Hello everyone,

I’m encountering a frustrating issue with my MonoGame application on Windows, and I’m hoping someone here might have some insight. Whenever I try to launch my game on Windows, it crashes immediately without any error message. I’ve checked the event logs, but there’s no helpful information there either.

I’ve tested the game on multiple machines running Windows 10 and Windows 11, but the issue persists across all of them. I’ve also made sure to update all my drivers and DirectX components, but still no luck.

I’ve been digging through the forums and documentation, but I haven’t found any solutions that work for my specific case. Has anyone else experienced something similar or have any suggestions for troubleshooting?

Thanks in advance

2 posts - 2 participants

Read full topic

What is the best way to solve two functions doing the same thing but moving different directions?

$
0
0

C# rookie here. Familiar with some coding basics, and it feels like something should exist to help fix this, but I’m not sure what.

I have a function that I use to move a square cursor around a square grid (modelPosition):

        public Vector2 pressAndHoldMoveUp(Vector2 MODELPOSITION)
        {
            Vector2 modelPosition = MODELPOSITION;
            float counterHoldLimit = 0.5f;
            //float keyCooldown = 0f;

            if (IsPressed(Keys.W))
            {

                //KEY Behaviour: move just once, when first pressed
                if (JustPressed(Keys.W))
                {
                    modelPosition = MoveUp(modelPosition);
                    keyCooldown = 0f;
                }
                //KEY Behaviour: If it wasn't first pressed, we need to wait--add the elapsed game time since last update call.
                else
                {
                    //keyCooldown = 0;
                    keyCooldown += Globals.Time;
                }
                //KEY Behaviour: if we've waited long enough (passed the counterHoldLimit), it will move the position once, and then reset keyCooldown to 1/3.5th the counterHoldLimit
                if (keyCooldown > counterHoldLimit)
                {
                    modelPosition = MoveUp(MODELPOSITION);
                    keyCooldown = keyCooldown - (counterHoldLimit / 3.5f);
                }
            }
            return modelPosition;
        }
        public Vector2 pressAndHoldMoveDown(Vector2 MODELPOSITION)
        {
            Vector2 modelPosition = MODELPOSITION;
            float counterHoldLimit = 0.5f;
            //float keyCooldown = 0f;

            if (IsPressed(Keys.S))
            {

                //KEY Behaviour: move just once, when first pressed
                if (JustPressed(Keys.S))
                {
                    modelPosition = MoveDown(modelPosition);
                    keyCooldown = 0f;
                }
                //KEY Behaviour: If it wasn't first pressed, we need to wait--add the elapsed game time since last update call.
                else
                {
                    //keyCooldown = 0;
                    keyCooldown += Globals.Time;
                }
                //KEY Behaviour: if we've waited long enough (passed the counterHoldLimit), it will move the position once, and then reset keyCooldown to 1/3.5th the counterHoldLimit
                if (keyCooldown > counterHoldLimit)
                {
                    modelPosition = MoveDown(MODELPOSITION);
                    keyCooldown = keyCooldown - (counterHoldLimit / 3.5f);
                }
            }
            return modelPosition;
        }

The only difference is that one uses the W key to move up while the other uses the S key to move down. It feels like there should be a way to simplify to use only one function where I pass in the direction (up/down) and the respective key. However, I’m not sure how I could pass in a function and key.

Any ideas? Thanks for help.

4 posts - 2 participants

Read full topic

3D models in .NET MAUI project

$
0
0

Hi everyone,
I just got hired at a new company. They have a mobile app where you should be able to see 3D models. The 3D models are created by a third part app. So I need to find a way to implement these 3D models into the .NET 7 MAUI mobile app project.
The mobile app is an IOS app and we are working with Windows. If we had MacBooks, then Xcode would have some libraries we could use for this task. But how do I do with Windows and what libraries could be used?
I googled an I got this result: MonoGame is a library or framework that supports loading and rendering 3D models. Therefore im hoping someone can help me :pray:t3:

1 post - 1 participant

Read full topic

Can't compile android project

$
0
0

I installed all the dependencies, I can run a regular Xamarin app without errors, but I can’t run the MonoGame app. When I try to compile a newly created or downloaded example android project, dotnet gives the following errors:

C:\Program Files\dotnet\sdk\8.0.200\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.EolTargetFrameworks.targets(38,5): err
or NETSDK1202: The "net6.0-android" workload is not supported and will not receive security updates.  More information about the support policy: https://aka.ms/maui-support-policy.  [C:\dev\AndroidXNATest\And
roidXNATest.csproj]
C:\Program Files\dotnet\sdk\8.0.200\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.EolTargetFrameworks.targets(38,5): err
or NETSDK1202: The "net6.0-android" workload is not supported and will not receive security updates.  More information about the support policy: https://aka.ms/maui-support-policy.  [C:\dev\AndroidXNATest\And
roidXNATest.csproj]

Application with DesktopGL runs fine.
Thank you in advance!

1 post - 1 participant

Read full topic

How to get a correct SSAO result?

$
0
0

I’m new to shader and I’m going to implement SSAO in my project. I use a logic like this:

float4 MainPS(VertexShaderOutput input) : COLOR
{
    float3 fragPos = VSPositionFromDepth(input.TexCoords );
   
    
        
    
    float occlusion = 0.0;
    float radius =1;
      
    float3 sampleZ = float3(0, 0, 0);
    sampleZ = fragPos + sampleZ;
        
      
    float4 offsetZ = float4(sampleZ, 1.0);
    offsetZ = mul(projection, offsetZ);  
    offsetZ.xy /= offsetZ.w;  
    offsetZ.xy = offsetZ.xy * 0.5 + 0.5; 
      
    float sampleDepthZ = tex2D(gProjectionDepth, offsetZ.xy).r * 2 - 1;
    for (int i = 0; i < 16; ++i)
    {
   
        float3 sample = samples[i] ;
        sample =  fragPos+ sample;
        
       
        float4 offset = float4(sample, 1.0);
        offset = mul(projection , offset); 
        offset.xy  /= offset.w; 
        offset.xy  = offset.xy  * 0.5 + 0.5; 
     
       
        float sampleDepth = tex2D(gProjectionDepth, offset.xy).r* 2 - 1;
 
        occlusion += (sampleDepth > sampleDepthZ ? 0.0 :1.0);
         
    }
    
    occlusion = 1.0- (occlusion / 16);
    return float4(occlusion, occlusion, occlusion, 1);

}

float3 VSPositionFromDepth(float2 vTexCoord)
{
    // Get the depth value for this pixel
    float z = tex2D(gProjectionDepth, vTexCoord).r*2-1;
    // Get x/w and y/w from the viewport position
    float x = vTexCoord.x*2-1  ;
    float y = (1 - vTexCoord.y) * 2 - 1;
    float4 vProjectedPos = float4(x, y, z, 1 );
    // Transform by the inverse projection matrix
    float4 vPositionVS = mul(vProjectedPos, g_matInvProjection);
   
    // Divide by w to get the view-space position
    return vPositionVS.xyz / vPositionVS.w;
}

The pixel shader uses a clip space depth map and an array of sample points. First get the view-space position of the pixel, then transform it to clip space and sample depth as the center depth of the sample kernel, then use the same method to get the depth value of every random sample point, compare these depth values with the center depth value and get a result. The method sounds right but I got wrong result, the ao texture is like that:

The result texture is small and even glitchy if I rotate the camera. I cannot figure out why the texture is small all the time and I have been stuck here for three days. Am I going to completely rewrite the shader?

the geometry buffer shader is like that:

matrix World;
matrix View;
matrix Projection;

struct VertexShaderInput
{
    float4 Position : POSITION0;
    float3 Normal : NORMAL0;
    float2 TexureCoordinate : TEXCOORD0;
    float3 Tangent : TANGENT0;
};

struct VertexShaderOutput
{
    float4 Position  : SV_Position;
    float4 PositionV : TEXCOORD1;
    
    float4 PositionP : TEXCOORD4;
    float3 Normal : TEXCOORD2;
    float3 Tangent : TEXCOORD3;
};
struct PixelShaderOutput
{
    
    float4 ViewPosition : COLOR0;
    float4 ProjectionDepth : COLOR1;
    float4 Normal : COLOR2;
};

float3x3 inverse_mat3(float3x3 m)
{
    float Determinant =
       m[0][0] * (m[1][1] * m[2][2] - m[2][1] * m[1][2])
     - m[1][0] * (m[0][1] * m[2][2] - m[2][1] * m[0][2])
     + m[2][0] * (m[0][1] * m[1][2] - m[1][1] * m[0][2]);
    
    float3x3 Inverse;
    Inverse[0][0] = +(m[1][1] * m[2][2] - m[2][1] * m[1][2]);
    Inverse[1][0] = -(m[1][0] * m[2][2] - m[2][0] * m[1][2]);
    Inverse[2][0] = +(m[1][0] * m[2][1] - m[2][0] * m[1][1]);
    Inverse[0][1] = -(m[0][1] * m[2][2] - m[2][1] * m[0][2]);
    Inverse[1][1] = +(m[0][0] * m[2][2] - m[2][0] * m[0][2]);
    Inverse[2][1] = -(m[0][0] * m[2][1] - m[2][0] * m[0][1]);
    Inverse[0][2] = +(m[0][1] * m[1][2] - m[1][1] * m[0][2]);
    Inverse[1][2] = -(m[0][0] * m[1][2] - m[1][0] * m[0][2]);
    Inverse[2][2] = +(m[0][0] * m[1][1] - m[1][0] * m[0][1]);
    Inverse /= Determinant;
    
    return Inverse;
} 
 
 
VertexShaderOutput MainVS(in VertexShaderInput input)
{
	VertexShaderOutput output = (VertexShaderOutput)0;
	
    float4 worldPosition = mul(input.Position, World);
    float4 viewPosition = mul(worldPosition, View);
    output.Position  = mul(viewPosition, Projection);
    
    output.PositionV = viewPosition;
    output.PositionP = mul(viewPosition, Projection);
    float3x3 worldView =   World*View;
    float3x3 normalMatrix = transpose(inverse_mat3(worldView));
     output.Tangent = mul(input.Tangent , normalMatrix);
    
    output.Normal = mul(input.Normal, normalMatrix);
     
	return output;
}

PixelShaderOutput MainPS(VertexShaderOutput input) 
{
    PixelShaderOutput psOut = (PixelShaderOutput) 0;
   
    psOut.ViewPosition.xyz = input.PositionV.xyz *0.5+0.5 ;
    psOut.ViewPosition.a = (input.PositionP.z /50) ;
   
    psOut.ProjectionDepth.rgb = (input.PositionP.z / input.PositionP.w)*0.5+0.5;
    psOut.ProjectionDepth.a = 1;
    psOut.Normal = float4(normalize(input.Normal) * 0.5 + 0.5, 1);
    return psOut;

}

It seems that the width and height value of the small AO texture is 0.1 times the whole texture width and height, but I haven’t found any 0.1 mulplication mistakes in my code. Why?

2 posts - 1 participant

Read full topic

MonoGame source Rectangle not working

$
0
0

Hello, so,
I have ran into an issue where, I’m trying to add collisions into my game, to do this I need to have a relative rectangle,

so, in a simple case it works,

_spriteBatch.Draw(DoomWalkUp1, PlayerHitbox, Color.White);

when i test this with intersections, it works fine, however when I apply it to my main character, he doesn’t even spawn in, nor does he move or anything, (I debug his coordinates)

Main which doesn’t work -

_spriteBatch.Draw(CurrentFrame, CharacterPosition, PlayerHitbox, Color.White, 0f, new Vector2(DoomWalkUp1.Width/2, DoomWalkUp1.Height/2),
Vector2.One, SpriteEffects.None, 0f);

Main which works -

_spriteBatch.Draw(CurrentFrame, CharacterPosition, null, Color.White, 0f, new Vector2(DoomWalkUp1.Width/2, DoomWalkUp1.Height/2),
Vector2.One, SpriteEffects.None, 0f);

notice how in the one that works, I do not use a source rectangle, and instead I use ‘null’

where the source rectangle is declared in load content

PlayerHitbox = new Rectangle(CharacterPosX, CharacterPosY, 46, 58);

So, does anyone know how to apply the rectangle to the main character without causing issues?

2 posts - 2 participants

Read full topic

Scaling drop shadows in 2d.... "directional scaling" or "directional foreshortening."

$
0
0

I already HAVE working geometry shadows, in my 2d game…
Geometry, such as walls and platforms, which physically connect to the back wall, cast polygon shadows away from the light. Familiar to a lot of you.

NOW, I am working on shadows for objects and doodads, which do NOT connect with the back wall… So, they should have drop shadows, instead… Floating shadows, under the objects. Will use for pillars and pipes etc, stuff that “floats” off the back wall…
I want the shadows to SCALE with distance to the light source…

This is fairly easy to achieve by itself…

The REAL challenge, is I want adjacent sprites shadows to still connect at the seams, seamlessly, so the scaling needs to be rather specific.
-In other words, corners need to stay together…

Here is an exaggerated mock up of what I think I want… you can see shadows scaling smaller with increased distance from the light source, so shadows get bigger closer to the light… You can see the tile at the CENTER has a SQUARE shadow under it, and every tile going out from there, is made narrower as it goes out the axis…

The picture shows it, but I don’t have the words. Any help or discussion appreciated… Will even accept notes on how to improve question.

1 post - 1 participant

Read full topic


Cannot load .tmx file. System.IO.EndOfStreamException: 'Unable to read beyond the end of the stream.'

$
0
0

line

_tiledMap = Content.Load<TiledMap>("samplemap");

return error “System.IO.EndOfStreamException: ‘Unable to read beyond the end of the stream.’”

Details:

System.IO.EndOfStreamException
  HResult=0x80070026
  Message=Unable to read beyond the end of the stream.
  Source=System.Private.CoreLib
  StackTrace:
   at System.ThrowHelper.ThrowEndOfFileException()
   at System.IO.BinaryReader.ReadString()
   at MonoGame.Extended.Tiled.TiledMapReader.ReadProperties(ContentReader reader, TiledMapProperties properties)
   at MonoGame.Extended.Tiled.TiledMapReader.ReadLayer(ContentReader reader, TiledMap map)
   at MonoGame.Extended.Tiled.TiledMapReader.ReadGroup(ContentReader reader, TiledMap map)
   at MonoGame.Extended.Tiled.TiledMapReader.ReadLayers(ContentReader reader, TiledMap map)
   at MonoGame.Extended.Tiled.TiledMapReader.Read(ContentReader reader, TiledMap existingInstance)
   at Microsoft.Xna.Framework.Content.ContentTypeReader`1.Read(ContentReader input, Object existingInstance)
   at Microsoft.Xna.Framework.Content.ContentReader.InnerReadObject[T](T existingInstance)
   at Microsoft.Xna.Framework.Content.ContentReader.ReadObject[T]()
   at Microsoft.Xna.Framework.Content.ContentReader.ReadAsset[T]()
   at Microsoft.Xna.Framework.Content.ContentManager.ReadAsset[T](String assetName, Action`1 recordDisposableObject)
   at Microsoft.Xna.Framework.Content.ContentManager.Load[T](String assetName)
   at Test3.Game1.LoadContent() in D:\MonoGameProjects\Test3\Game1.cs:line 33
   at Test3.Game1.Initialize() in D:\MonoGameProjects\Test3\Game1.cs:line 28
   at Microsoft.Xna.Framework.Game.DoInitialize()
   at Microsoft.Xna.Framework.Game.Run(GameRunBehavior runBehavior)
   at Program.<Main>$(String[] args) in D:\MonoGameProjects\Test3\Program.cs:line 3

File Content.mgcb

#-------------------------------- References --------------------------------#
/reference:MonoGame.Extended.Content.Pipeline.dll
/reference:MonoGame.Extended.dll
/reference:MonoGame.Extended.Tiled.dll

#---------------------------------- Content ---------------------------------#

File .csproj


    <PackageReference Include="MonoGame.Extended" Version="3.9.0-alpha0079" />
    <PackageReference Include="MonoGame.Extended.Content.Pipeline" Version="3.9.0-alpha0079" />
    <PackageReference Include="MonoGame.Extended.Tiled" Version="3.9.0-alpha0079" />
    <PackageReference Include="MonoGame.Framework.DesktopGL" Version="3.8.1.303" />
    <PackageReference Include="MonoGame.Content.Builder.Task" Version="3.8.1.303" />

Game1.cs


using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

using MonoGame.Extended.Tiled;
using MonoGame.Extended.Tiled.Renderers;
using System.Reflection.PortableExecutable;
using System;
using Test3;

namespace Test3
{
    public class Game1 : Game
    {
        private GraphicsDeviceManager _graphics;
        private SpriteBatch _spriteBatch;
        TiledMap _tiledMap;
        TiledMapRenderer _tiledMapRenderer;

        public Game1()
        {
            _graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            IsMouseVisible = true;
        }

        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        protected override void LoadContent()
        {
            _tiledMap = Content.Load<TiledMap>("samplemap");
            _tiledMapRenderer = new TiledMapRenderer(GraphicsDevice, _tiledMap);

            _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();

            // TODO: Add your update logic here
            _tiledMapRenderer.Update(gameTime);

            base.Update(gameTime);
        }

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

            _tiledMapRenderer.Draw();
            base.Draw(gameTime);
        }
    }
}

1 post - 1 participant

Read full topic

Rollback Netcode Library

$
0
0

I’ve been working on a dotnet library for Rollback Netcode, widely used by fighting games to accomplish a better P2P multiplayer experience

I based my implementation on GGPO which was the pioneer in the netcode implementation

More about why it is good and how it works here and here.

It is very early and needs more testing and docs. but I believe it looks good enough to share :sweat_smile:

Monogame local network demo:

Backdash - Rollback NetCode - MonoGame - 4 player 2 spectators

Monogame online lobby demo:

Backdash - Rollback NetCode - MonoGame - online lobby

1 post - 1 participant

Read full topic

Collisions movement issue

$
0
0

Hello, I was wandering if someone could help me with a small collisions issue,
I’m working on a school project in monogame that I started around a year ago, I just realized how quickly the deadline for it arrived and now I have to pick up where I left off,
I’ve made a simple collider but it doesn’t seem to want to implement very well,

The problem is that my character doesn’t move, all of his animations work fine, I debugged his coordinates, they update fine too, but he just stays in the same spot.
Here is the drawing code:

_spriteBatch.Draw(CurrentFrame, PlayerHitbox, null, Color.White, 0f, new Vector2(DoomWalkUp1.Width / 2, DoomWalkUp1.Height / 2), SpriteEffects.None, 0f);

Now, my previous code, before I added the destination rectangle
looked like this

_spriteBatch.Draw(CurrentFrame, CharacterPosition, null, Color.White, 0f, new Vector2(DoomWalkUp1.Width/2, DoomWalkUp1.Height/2),
Vector2.One, SpriteEffects.None, 0f);

this works fine, walks coordinates update, animations animate, and most importantly, visually moves.

If anyone has any suggestions, want more code, please say.

1 post - 1 participant

Read full topic

Extended tiled manager not showing up in the contenet manager

$
0
0

I have been tinkering with the monogame extended tiled system manager and have recently moved to a new environment. I know that to get the manager to build tiled files, you have to add a reference to the Nuget file, and I have done so, but the recent build and import settings for tiled files have not appeared and selectable options.
would appreciate if any one knew what was up with that.

Thanks.

1 post - 1 participant

Read full topic

Stop drawing the screen to debug

$
0
0

Hello Monogame community,

I wanted to add a way to completely freeze my game to make debugging easier, but when I stop drawing the screen, the display keeps alternating between two frames.

bug

Is there some constraints to what we can do with the Draw function?
Also, I think I should still call the base.Update and base.Draw even if the game is freezed, what do you think?

Update

//Freezing the screen on F12 input
KeyboardState keyboardState = Keyboard.GetState();
if (keyboardState.IsKeyDown(Keys.F12))
{
    if (!freezeToggled)
    {
        freezed = !freezed;
        freezeToggled = true;
    }
}
else
   freezeToggled = false;

if (!freezed)
{
    //Just making the texture move
    X += Vx;
    
    if (X > 800 - 256) { Vx = -8; }
    if (X < 0) { Vx = 8; }
}

base.Update(gameTime);

Draw

if (!freezed)
{
    GraphicsDevice.Clear(Color.CornflowerBlue);
    
    spriteBatch.Begin(samplerState: SamplerState.PointClamp);
    spriteBatch.Draw(Grass, new Rectangle(X, 0, 256, 256), Color.White);
    spriteBatch.End();
}
base.Draw(gameTime);

1 post - 1 participant

Read full topic

understand my dottrace

$
0
0


I ran a dot-trace on my project , was wondering if anyone could help me understand please?
Thread 1 is where my code runs (i only get 33%?)
I loose 22% of that 33% on System.Threading.Thread.Sleep?
Is it part of framerate managment?

Anyone knows what happens in the other threads?

2 posts - 2 participants

Read full topic

Clamp Sampling to Inside Source Rectangle

$
0
0

In my 2D game, I have a glitch effect shader that samples a texture 3 times per pixel, and each time I sample with a different UV offset. I would then combine the samples into a glitchy look. I’m also using a texture atlas (i.e., all my textures are on one big texture, and I use source rectangles to choose which “subtexture” to render).

This unfortunately means that my pixel shader might sample pixels from outside of the source rectangle, which causes the shader to sample pixels on the atlas texture that belongs to other “subtextures”.

Is there a way to prevent the pixel shader from sampling outside of the source rectangle passed to SpriteBatch?

I thought of using effect parameters to store the source rectangle and clamp the offseted UV in my pixel shader, but I would need to begin a new sprite batch for each subtexture that uses this glitch effect, as each “subtexture” would have a different source rectangle.

I also thought of passing the source rectangle information into the vertex data. Then I could use a custom vertex shader like the one in this post I created. This is the best way I can think of, but I’m wondering if there is a better way to achieve this.

1 post - 1 participant

Read full topic


[Resolved] How do you have a game object move is a sinewave pattern?

$
0
0

Hey folks,

As my first beginner game, I’m building a vertical shooter.

I want the enemy ships to move in a sinewave pattern;

Despite my research on trigonometry and coding implementations, am spectacularly failing at this simple task.

What’s Happening

I recorded a video showing what my movement looks like.

While I do have movement that somewhat resembles a sinewave pattern, I fail to control the speed at which it moves along the x-axis.

So when I get this super fast-moving wave.

I have a video but since I’m a new users I am restricted to one external link in this topic.

What I Want To Happen

This is a video that implements this sinewave solution (using Unity).

The difference is this is a horizontal shooter.

My code is quite similar to their implementation

Enemies and Sine Waves | MAKE A SHMUP game like GRADIUS #3 - Unity How to Tutorial

Implementation Example

This is my function, which results in the movement of my enemy object, and it is called in the Update game loop.

// param value
float seconds = (float)gameTime.ElapsedGameTime.TotalSeconds;

// movement function
  public void MoveSinWave(float seconds) {
      float amplitude = 50f;
      float frequency = 50f;
      float sinX = System.MathF.Sin(position.Y * frequency) * amplitude;
      position.X = sinCenterX + sinX;
      position.Y += MathF.Round(speed * seconds);
  } 

Considerations

All examples I see use the opposite position (in my case, the Y position) to drive the radian value in the Sin math function.

I would think that I could just create a different value that controls the rate of speed, but I don’t see any other implementation requiring to do this (and I have yet to test if this might produce more desirable results)

Any suggestions about my code or just my math logic here is greatly appreciated :pray:

4 posts - 1 participant

Read full topic

Need Help with Mobile Game Performance in Monogame

$
0
0

Hello Monogame Community,

I’m currently working on a mobile game using Monogame and encountering performance issues, particularly on lower-end devices. Despite trying various optimizations, I’m still struggling to achieve consistent performance across different devices. I would greatly appreciate any insights, tips, or best practices from the community on how to improve performance and optimize the game for a wider range of devices.
I also check this: Using Monogame with Tiled and Monogame.Extendedgen ai but I have not found any solution.
Thank you all for your help and support.

Regards
Mia smith

2 posts - 2 participants

Read full topic

Shader runs in OpenGL, but crashes in DirectX

$
0
0

I have a shader that builds and runs fine when working with an OpenGL project, but crashes when loaded in a DirectX project. It does build, but when loaded it crashes and gives an Invalid Arguments exception. It does not tell me which argument is invalid.

#if OPENGL
#define SV_POSITION POSITION
#define PS_SHADERMODEL ps_3_0
#define VS_SHADERMODEL vs_3_0
#else
#define PS_SHADERMODEL ps_4_0
#define VS_SHADERMODEL vs_4_0
#endif

sampler2D TextureSampler : register(s0);

struct VertexShaderOutput
{
float4 Position : SV_POSITION0;
float4 Color : COLOR0;
float2 Tex : TEXCOORD0;
};

matrix Projection;

struct VsInput
{
float4 Position : POSITION0;
float4 Color : COLOR0;
float2 TexureCoordinateA : TEXCOORD0;
};

VertexShaderOutput MainVS(VsInput input)
{
VertexShaderOutput output;
output.Position = mul(input.Position, Projection); // Transform by WorldViewProjection
output.Color = input.Color;
output.Tex = input.TexureCoordinateA;
return output;
}

float4 MainPS(VertexShaderOutput input) : COLOR
{
float4 color = tex2D(TextureSampler, input.Tex);
float average = (color.r + color.g + color.b) / 3;

average = int(average * 25) / 25.0;

color.rgb = average;
return color;

}

technique BasicColorDrawing
{
pass P0
{
VertexShader = compile VS_SHADERMODEL MainVS();
PixelShader = compile PS_SHADERMODEL MainPS();
}
};

I am using MonoGame 3.8.1.303.

1 post - 1 participant

Read full topic

Matrix Projection Camera - Aligning Spritebatch and GPU Instance

$
0
0

Hey,
i know there have been several posts about this already, and i really didn’t want to post, but i just cant get it to work. Tinkering around for days now.

I want to align a spritebatch draw like this:

spriteBatch.Begin(transformMatrix: camera.worldViewProjSpriteBatch);
spriteBatch.Draw(texture, position, null, Color.White, 0, new(texture.Width / 2f, texture.Height / 2f), scale, SpriteEffects.None, layer);
spriteBatch.End();

with a quad i’ve drawn with a vertexbuffer:

float4 position = float4(vertexInput.Position.xy * textureSize + instanceInput.Position.xy, 0.0, 1.0);
output.Position = mul(position, worldViewProjGPU);

and these are my matrices for the cameras:

// SpriteBatch
var transformMatrix = Matrix.CreateTranslation(-player.position.X, -player.position.Y, 0);
transformMatrix *= Matrix.CreateScale(distance, distance, 1); // Scale by zoom
transformMatrix *= Matrix.CreateTranslation(windowSize.X * 0.5f, windowSize.Y * 0.5f, 0);
worldViewProjSpriteBatch = transformMatrix;

// GPU Instance
Matrix viewMatrixGPU = Matrix.CreateLookAt(V(player.position, 10), V(player.position, 0), Vector3.Up);
Matrix projectionMatrixGPU = Matrix.CreateOrthographicOffCenter(0, windowSize.X, windowSize.Y, 0, nearPlane, farPlane);
projectionMatrixGPU *= Matrix.CreateScale(distance, distance, 1);
worldViewProjGPU = viewMatrixGPU * projectionMatrixGPU;

V = Vector, distance is the zoom. And this kinda works, but the sprite’s scale and position dont align with the quad ones. And i’m just not getting something fundamentally. Like one is in screenspace and one in worldspace or something. If somebody could make me understand this, i would be really appreciative!

3 posts - 2 participants

Read full topic

Does using dotNET 8 (or even 6 or 5) stops me from publishing to consoles and mobile?

$
0
0

If I’m not mistaken, nothing is preventing one from using MonoGame 3.8 targeting dotnet 8 but I’m confused if the dotnet version will stop me from releasing my games on other platforms other than desktop (Mac, Windows, Linux) such as consoles (Switch, Playstation, Xbob) and mobile (Android and iOS).

I’d like to use the latest dotnet but only if this will not be an impedance to port my games. So, can I use whatever dotnet version I want or is it better to stick to a specific version such as dotnet 4, 5, or 6?

3 posts - 1 participant

Read full topic

Easy way to create shadow map for 2D game?

$
0
0

I’m new to Monogame and looking for easy method for create shadow map for my top-down rpg game. Lighting was implemented via per-pixel lighting.

Light source class looks like this:

public class Light
{
    public Vector2 Position { get; set; }
    
    public float Radius { get; set; }

    public Color Color { get; set; }

    public float Intensity { get; set; }
}

I know that a light-view-projection matrix is needed, I tried to get it, but I’m not sure if it works correctly:

var lightDirection = Vector3.Normalize(lightPosition - position);

var viewMatrix = Matrix.CreateLookAt(
    lightPosition,
    lightPosition + lightDirection,
    Vector3.One
);
var projectionMatrix = Matrix.CreateOrthographic(
    0.1f,
    0.1f,
    -1,
    1
);

var lightViewProjectionMatrix = viewMatrix * projectionMatrix;

1 post - 1 participant

Read full topic

Shadow Mapping Implementation

$
0
0

Hello

I’m relatively new to MonoGame and currently working on implementing shadow mapping for my top-down RPG game. I’ve been trying to create a light-view-projection matrix for shadow mapping, but I’m encountering some challenges. Despite my efforts, I’m unsure if my approach is correct.

Here’s a snippet of my code for creating the light-view-projection matrix:

// Code snippet for creating light-view-projection matrix
var cameraPosition = new Vector3(camera.Position.X, camera.Position.Y, /* Adjust Z position as needed /);
var lightDirection = Vector3.Normalize(light.Position - cameraPosition);
var viewMatrix = Matrix.CreateLookAt(
cameraPosition,
cameraPosition + lightDirection,
Vector3.Up // Adjust up vector as needed
);
float nearPlane = /
Adjust near plane value based on your game world /;
float farPlane = /
Adjust far plane value based on your game world /;
var projectionMatrix = Matrix.CreateOrthographicOffCenter(
/
Adjust left, right, bottom, and top values based on your game world */,
nearPlane,
farPlane
);
var lightViewProjectionMatrix = viewMatrix * projectionMatrix;
I’d appreciate any insights or suggestions on how to correctly create the light-view-projection matrix for shadow mapping in MonoGame. I have checked General - Community | MonoGamesalesforce cpq

Are there any adjustments or improvements that I should make to my code?

Thank you in advance for your help.

Best regards,
stevediaz

1 post - 1 participant

Read full topic


SetRenderTarget crashes the game

$
0
0

Hi! I’m quite new to monogame I use it on a school project, I have a problem with RenderTarget2D and SetRenderTarget. I have a map class:

public class Map
{
    private RenderTarget2D _target;
    public const int TILE_SIZE = 128;
    public static readonly int[,] tiles = {
        {1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
        {1, 0, 0, 1, 0, 1, 0, 1, 0, 1},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
        {1, 1, 0, 1, 0, 1, 0, 1, 0, 1},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
        {1, 1, 0, 1, 0, 1, 0, 1, 0, 1},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
        {1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
    };
    Texture2D wall = Globals.Content.Load<Texture2D>("wall");

    public Map()
    {
        _target = new(Globals.GraphicsDevice, tiles.GetLength(1) * TILE_SIZE, tiles.GetLength(0) * TILE_SIZE);
        Activate();
        DrawMap();
        Globals.GraphicsDevice.SetRenderTarget(null);
    }

    public void Explosion()
    {
        tiles[0,0] = 0;
        Activate();
        DrawMap();
        Globals.GraphicsDevice.SetRenderTarget(null);
    }

    public void Activate(){
        Globals.GraphicsDevice.SetRenderTarget(_target);
        Globals.GraphicsDevice.Clear(Color.Transparent);
    }

    public void DrawMap(){
        Globals.SpriteBatch.Begin();
        for (int i = 0; i < tiles.GetLength(0); i++)
        {
            for (int j = 0; j < tiles.GetLength(1); j++)
            {
                if (tiles[i, j] == 1)
                {
                    var posX = j * TILE_SIZE;
                    var posY = i * TILE_SIZE;
                    Globals.SpriteBatch.Draw(wall, new Vector2(posX, posY), Color.White);
                }

                

            }
        }
        Globals.SpriteBatch.End();
    }

    public void Draw()
    {
        Globals.SpriteBatch.Draw(_target, Vector2.Zero, Color.White);
    }

    public void Update()
    {

    }
}

In my GameManager classes Init method which is called in the LoadContent method of Game1 class, I make a map instance. And it works fine, until I try to redraw the map layout because an explosion happens, but my game crashes at line Globals.GraphicsDevice.SetRenderTarget(_target); in Activate(). I got Exception thrown: ‘System.InvalidOperationException’ in MonoGame.Framework.dll; message in the debug console. Any idea what causing it or what am i missing?
Any answears are appreciated!

1 post - 1 participant

Read full topic

Kni engine + BlazorGL so slow reason

$
0
0

I’ve just made my game working on BlazorGL and it runs on ~0.2fps. Game is working fine on OpenGL. I tried to run browser profiler and of course this info is pretty useless. Does anyone have any ideas on how to speed up Blazor or where to look for code that slows down rendering?

1 post - 1 participant

Read full topic

Could Someone help me Guidance on Implementing Advanced Camera Controls in MonoGame?

$
0
0

Hello there,

I am working on a game project and am looking to implement advanced camera controls using MonoGame. Mainly, I would like to achieve smooth, dynamic camera movements that follow the player character while allowing for zooming and rotation.

I have already implemented a basic camera system that follows the player, but I am struggling to add the additional functionality I mentioned. I have researched various techniques such as using matrices for transformations and lerping for smooth movements, but I am unsure how to integrate these into my existing code.

Could anyone provide guidance or point me to resources/tutorials that cover these advanced camera techniques in MonoGame?

Also, I have taken help from this: Best practice for using a camera in MonoGame? tableau which definitely help me out a lot.

I am particularly interested in examples that demonstrate how to smoothly zoom in/out and rotate the camera around the player.

Any help or advice would be greatly appreciated.

Thank you in advance for your assistance.

1 post - 1 participant

Read full topic

survivel

$
0
0

survivel game гра в якій потрібно виживати на невідомій планеті

1 post - 1 participant

Read full topic

MonoGame Content Builder on Mac M1

$
0
0

I just started developing on mac m1 and figured out that monogame is kind of a mess to get running on mac.
I installed
vscode
.NET x64 and arm64
dotnet-mgcb-editor

When running the mbcb it is failing because it is expecting old libraries

I read somewhere that people run mgcb from a windows docker image and mount the volume or something like this. Is there any source or setup on this?

2 posts - 1 participant

Read full topic

Sorting in a 2D Topdown Game

$
0
0

Hey!
How would i do the sorting so that my player can go behind trees and so on. And i would still want to be able to use shaders like a wind shader on the trees e.g… I’ve seen i would need multiple spritebatches for shaders. But i don’t know how to YSort the trees and the player then. I use BackToFront Sorting right now and if i set the depthstencil to default it works, but then i need to alpha clip the textures which looks ugly with my textures because they are hand drawn. Any ideas on what i could do? I already tried immediate rendering too but then sorting every object is very expensive the way i came up with. and then nothing would be batched, so the performance then is quiet bad. Does somebody have any idea on what i could do?

1 post - 1 participant

Read full topic

3D objects are drawn over each other. My depth buffering isn't working

$
0
0

Monogame depth buffering

Hey, I’m having trouble with overlapping 3d objects. My 3D rendered models/objects are drawn on top based on which draw method gets called last instead of basing it off the pixel’s position relative to the camera.

I asked in the Discord and I was told that either my “depth read” or “depth write” are failing. My “Depth read” is I assume setting the DepthStencilState to default:

            graphicsDevice.DepthStencilState = DepthStencilState.Default;

And the depth write is this right:

GraphicsDevice.Clear(Color.CornflowerBlue);
 GraphicsDevice.Clear(ClearOptions.DepthBuffer, Color.Black, 1.0f, 0);

I’ve tried everything. My only theory left is that I keep resetting the graphicsDevice Vertexbuffer by this line of code

                graphicsDevice.SetVertexBuffer(shape.vertexBuffer);

But ChatGPT informed me that isn’t a problem. Does anyone have an idea where my problem lies?

Here is how I draw my 3D objects

	public override void Draw(GameTime gameTime, SpriteBatch spriteBatch) {
            graphicsDevice.DepthStencilState = DepthStencilState.Default;
            graphicsDevice.BlendState = BlendState.Opaque; // Spritebatch sets it default to AlphaBlend

            base.Draw(gameTime, spriteBatch);
            Draw3DModels();
            Draw3DShapes();
        }

        private void Draw3DModels() {
            foreach (ThreeDGameObject threeDGameObject in ThreeDObjects) {
                Model model = threeDGameObject.model;
                foreach (ModelMesh mesh in model.Meshes) {
                    foreach (BasicEffect effect in mesh.Effects) {

                        // Transformations
                        Matrix worldMatrix = Matrix.CreateTranslation(threeDGameObject.Position) *
                            Matrix.CreateFromYawPitchRoll(threeDGameObject.Rotation.Y, threeDGameObject.Rotation.X, threeDGameObject.Rotation.Z);
                        effect.World = worldMatrix;
                        effect.View = camera.View;
                        effect.Projection = camera.Projection;

                        // Light
                        // effect.AmbientLightColor = new Vector3(1f, 0, 0);
                        // effect.EnableDefaultLighting();

                        // Other shader settings
                        effect.TextureEnabled = true;
                        effect.Alpha = threeDGameObject.Alpha;

                        effect.CurrentTechnique.Passes[0].Apply();
                    }

                    mesh.Draw();
                }
            }
        }

        private void Draw3DShapes() {
            basicEffect.Projection = camera.Projection;
            basicEffect.View = camera.View;
            basicEffect.World = camera.World;

            // Draw all shapes
            foreach (Shape shape in shapes) { 
                // Transformations
                Matrix worldMatrix = Matrix.CreateTranslation(shape.Position) *
                    Matrix.CreateFromYawPitchRoll(shape.Rotation.Y, shape.Rotation.X, shape.Rotation.Z);
                basicEffect.World = worldMatrix;

                graphicsDevice.SetVertexBuffer(shape.vertexBuffer);
                graphicsDevice.Indices = shape.indexBuffer;

                foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes) { 
                    pass.Apply();
                    graphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, shape.vertices.Length / 3);
                }
            }
        }

Could the problem be in the camera?

I am in Visual Studio Code
Monogame version: 3.8.1.303

1 post - 1 participant

Read full topic


KNI Engine / Blazor: How does touch screen on mobile platforms work?

$
0
0

Hello all! First time on these discussions!

I’ve been using MonoGame for a while and recently I’ve decided to write a game using the KNI fork with its Blazor platform. I posted my game on itch.io:

The game appears to work fine on regular computers. However, the touch screen doesn’t appear to work when running the game on mobile. For context, I’m using an iphone and I can see the game open, but touching the screen doesn’t appear to work. From the developer mode console, I can see “Failed to load resource: the server responded with a status 403 ().” for “…_framework/dotnet.js.mp” and “…_framework/dotnet.runtime.js.map”, however I don’t see any problematic files when examining the sources getting downloaded (i.e. under the browser developer mode’s network menu).

I’ve tried using TouchPanel, but no connection is ever established. I assume MouseState should be enough to detect when the user taps the screen and where.

If more information is needed from me, I can provide.

(this question is mostly directed to knast lol)

Thanks in advance for any help!

6 posts - 4 participants

Read full topic





Latest Images