xna – Monogame – Collision does not work and invisible walls

I recently experimented with Monogame and XNA (by Gamemaker) and decided to work on a simple collision system. Problem is displayed in the GIF.
Preview of the error

main collision

Each entity (short name for everything with properties) has some parameters. These are:

                public vector2 position;
public Vector2 Origin;
public Vector2 Velocity;
public vector2 speed;
public Color Color = Color.White;
public rectangle rectangle
return new rectangle ((int) position.X, (int) position.Y, _texture.Width, _texture.Height);


I've used blocks to check how the collision works on multiple objects side by side. Right now, it's not about optimization.
As you can see, to the right of each vertical block is an invisible wall. I can add multiples just to demonstrate:

Enter image description here

Let's get to the collision code. I wanted to do something similar to GMS2 and check if the box with the sprite at the specified position overlapped another entity in the game.
Since I need to know which page to touch in the future, I wrote my code in the entity class as follows:

                Protected Bool IsTouchingLeft (Vector2 pos, Entity entity)
return pos.X + _texture.Width> = entity.Rectangle.Left &&
pos.X <= entity.Rectangle.Left &&
               pos.Y + _texture.Height >= entity.Rectangle.Top &&
posy <= entity.Rectangle.Bottom;
    protected bool IsTouchingRight(Vector2 pos, Entity entity)
        return pos.X >= entity.Rectangle.Right &&
pos.X + _texture.Width> = entity.Rectangle.Right &&
pos.Y + _texture.Height> = entity.Rectangle.Top &&
pos.Y <= entity.Rectangle.Bottom;
Protected Bool IsTouchingTop (Vector2 pos, Entity entity)
Return Pos.X <= entity.Rectangle.Right &&
               pos.X + _texture.Width >= entity.Rectangle.Left &&
pos.Y + _texture.Height> = entity.Rectangle.Top &&
pos.Y <= entity.Rectangle.Top;
Protected Bool IsTouchingBottom (Vector2 pos, Entity entity)
Return Pos.X <= entity.Rectangle.Right &&
               pos.X + _texture.Width >= entity.Rectangle.Left &&
posy <= entity.Rectangle.Bottom &&
               pos.Y + _texture.Height >= entity.Rectangle.Bottom;

For these functions I use two variables, the position where a collision should take place and the entity with which it should collide.

And to simplify matters, if I just need to know if it's going to collide at all, I've added a PlaceMeeting feature.

                protected bool PlaceMeeting (Vector2 pos, Entity entity)
return IsTouchingLeft (pos, entity) ||
IsTouchingRight (pos, entity) ||
IsTouchingTop (pos, entity) ||
IsTouchingBottom (pos, entity);

It only checks if a collision with a specified object occurs at a specified point. (If you used GMS, you know what I want to do.)

Let's go to the movement script.
Player is a child of the Entity Class and has some new variables.

                private Vector2 move;
private float grav = 0.3f;
private Int32 input_left;
private Int32 input_right;
private bool input_up;

The entry is made as follows:

                                input_left = Convert.ToInt32 (Keyboard.GetState (). IsKeyDown (Keys.A));
input_right = Convert.ToInt32 (Keyboard.GetState (). IsKeyDown (Keys.D));
input_up = Keyboard.GetState (). IsKeyDown (Keys.Space);

The horizontal input is adjusted as a result of the easier movement. Here is the Move () function.

                private void move ()
move.X = (input_right - input_left);
Speed.X = movement.X * speed.X;
Speed.Y + = grav;
if (input_up)
Speed.Y = speed.Y;

And the Code Player Collision Code:

                                foreach (var entity in entity) // Displays all created entities
if (entity == this) // If it is a player, do not check the collision

// Horizontal collision
if (PlaceMeeting (new vector2 (position.X + velocity.X, position.Y), entity))
while (! PlaceMeeting (new Vector2 (Position.X + Math.Sign (Velocity.X), Position.Y), entity))
Position.X + = Math.Sign (Velocity.X);
Speed.X = 0;
// vertical collision
if (PlaceMeeting (new vector2 (Position.X, Position.Y + Speed.Y), Entity)) // Check if it will collide in one step
while (! PlaceMeeting (new Vector2 (Position.X, Position.Y + Math.Sign (Velocity.Y)), entity)) // checks if it will not collide in 1 pixel
Position.Y + = Math.Sign (Velocity.Y); // Increment pixel by pixel until it collides into 1 pixel
Speed. Y = 0; // stop the player

And then I increase the position with speed.

Position + = speed;

I've tried different collision methods and they work and look like this:

Other collision One

In the player class, I used this collision code instead:

                                                if (this.Velocity.X> 0 && IsTouchingLeft (Position + Velocity, Entity))
this.Velocity.X = 0;
if (this.Velocity.X < 0 && IsTouchingRight(Position + Velocity, entity))
                this.Velocity.X = 0;
            //Vertical Collision
            if (this.Velocity.Y > 0 && IsTouchingTop (position + speed, entity)
this.Velocity.Y = 0;
if (this.Velocity.Y <0 && IsTouchingBottom (position + velocity, unit))
this.Velocity.Y = 0; 

Basically, I could not move to the left when I was to the right of vertical blocks.

Other collision 2

I also tried using this strange code with Rectangle.Intersects ().

                                                // Horizontal collision
var xRect = new rectangle ((int) position.X + (int) velocity.X, (int) position.Y, _texture.Width, _texture.Height);
if (xRect.Intersects (entity.Rectangle))
xRect = new rectangle ((int) Position.X + Math.Sign (Velocity.X), (int) Position.Y, _texture.Width, _texture.Height);
while (! xRect.Intersects (entity.Rectangle))
Position.X + = Math.Sign (Velocity.X);
this.Velocity.X = 0;

// vertical collision
var yRect = new rectangle ((int) position.X, (int) position.Y + (int) velocity.Y, _texture.Width, _texture.Height);
if (yRect.Intersects (entity.Rectangle))
yRect = new rectangle ((int) position.X, (int) position.Y + Math.Sign (Velocity.Y), _texture.Width, _texture.Height);
while (! yRect.Intersects (entity.Rectangle))
Position.Y + = Math.Sign (Velocity.Y);
this.Velocity.Y = 0;


This has made my program not to react.
Anyway, do you have any idea why that is?
I will post the full code of each class:

Implement a scrollable panel in XNA / MonoGame

I'm trying to create a scroll box for my game. The code I showed below is working but there is a problem.

I read Andrew's answer here and decided to implement the scrolling effect using a translation matrix. However, my controls (buttons, combo boxes, and so on) have a solid rectangle on the screen (the rectangle I use to check if the cursor is over the control). As I found out, the matrix translation only moves the texture of the control, not the rectangle.

The problem:

So, when I scroll down and click where the button was originally in the panel, the Click event fires even though the button's texture is "out of the box." scissorRectangle,

What I have considered:

  1. I thought I should disable the interaction with controls outside of scissorRectangleBut what about controls that are still partially visible?

  2. If the matrix translation does not work, I thought about going through the panels _controls List the offset and send it to each control (ugh) where it adjusts its rectangle position. : /

I have the following code for my panel:

// ...
private RasterizerState _rasterizerState = new RasterizerState () {ScissorTestEnable = true};
private Vector2 _scrollOffset = Vector2.Zero;
private matrix _matrix = Matrix.Identity;
// ...

in the To update():

_matrix = Matrix.CreateTranslation (new Vector3 (_scrollOffset, 0));
if (Enables && BorderBox.Intersects (inputManager.MouseRect))
if (inputManager.ScrolledDown ())
if (_combinedRowHeight - (ContentBox.Height -scrollOffset.Y)> -combinedTextHeight)
_scrollOffset.Y - = 14;
otherwise if (inputManager.ScrolledUp ())
if (_scrollOffset.Y <0)
_scrollOffset.Y + = 14;

And then in To draw():

// Save the previous RasterizerState
RasterizerState oldState = spriteBatch.GraphicsDevice.RasterizerState;
// Save the original scissors rectangle
Rectangle currentScissorRect = spriteBatch.GraphicsDevice.ScissorRectangle;

spriteBatch.End ();

spriteBatch.Begin ();
// Draw the control panel
spriteBatch.End ();

spriteBatch.Begin (SpriteSortMode.Immediate, BlendState.AlphaBlend, rasterizerState: _rasterizerState, transformMatrix: _matrix);

spriteBatch.GraphicsDevice.ScissorRectangle = ContentBox;

if (_drawControls)
for (int i = 0; i <_rows.Count; i ++)
_Reihen[i].Draw (SpriteBatch);

spriteBatch.End ();

// Restore the scissors rectangle
spriteBatch.GraphicsDevice.ScissorRectangle = currentScissorRect;

// Restore the RasterizerState
spriteBatch.Begin (rasterizerState: oldState);

Is there no other way? Should I simply send the offset to controls and change their position? Can not the matrix approach be used for interactive controls?

xna – Blender export does not render correctly in Monogame

I use monogame under Linux and Blender.

I have exported my model with the export program "FBX 7.4 Binary". Here is a render of Blender:

Enter image description here

However, when rendered by monogame, it does not look right:

Enter image description here

My rendering code is very normal (F #)

                let model = this.Content.Load @"Skull"

for mesh in model.Meshes do
for the effect in mesh.Effects do
Match effect with
| :? BasicEffect as effect ->
effect.EnableDefaultLighting ()
effect.TextureEnabled <- true
effect.PreferPerPixelLighting <- true

effect.World <-
Matrix.CreateScale (16.0f) *
Matrix.CreateTranslation (Vector3.Up * 32.0f + Vector3.Backward * 128.0f)

effect.View <- view
Effekt.Projektion <- projection
        | _ -> ()

mesh.Draw ()

How should I export models from Blender to use in Monogame?

xna – My position changes when dealing with animations

I'm trying to learn Monogames (Old XNA) and how to develop a 2d game.

I'm about to animate my sprites. It works, but there are things that seem strange to me.

For some reason, animating my sprites will "change" the animating position WITHOUT changing the origin. How so


If I have not changed my origin, my character "shifts" his body upwards. Something he should not do.

If I change the origin to the width and height of my frame, this does not happen. How so


It can be seen that the rectangle is still changing, but my character does NOT shift in its position. I can not really understand why he changes and does not change.

The origin is located in the upper left corner of the rectangle.

Why is my character position shifting? I think it's about compensating with the different heights of the frames. I'm not sure. I do not understand how to work with offset.

xna – How can I create a Metroid-like transition between two maps with Monogame Extended?

I want to make a transition like in the Metroid games. I use Monogame Extended and I have two TiledMaps. My idea was to place them right next to each other where the transition takes place, so I only have to move the camera from one card to the next. My problem now is that I have no idea how to put them next to each other. I thought they were in a coordinate system so I could move them, but I can not find a way to do that. Now I even wonder if this is actually the way to do it.

xna content pipeline – Load / Generate new resources when starting in MonoGame

I have a resource loading question at the beginning of my MonoGame game. I have several sprite sheets that I load at the beginning of the game. It takes about 5-10 seconds on my computer, but I have some reports that take up to a minute on other computers … that's far too long.
The reason is not loading the Texture2Ds, but writing new RenderTargets on startup. I have some colored sprite sheets where I generate a black and white version at startup. That costs time.

Now to my question: I was trying to do this later in the game so the game starts faster and I tried to start the color> black and white operation when the player made a new game – that would be a perfect one Situation to do it. However, I have always received two types of errors:

1st operation was not called for UI thread


2. Present can not be called if a render target is active

As you may have guessed, I'm doing the load operation in a separate thread so the UI will not freeze. The real problem, however, seems to be that I can not execute RenderTarget operations when I'm already doing Begin and End SpriteBatch operations.

How can I solve the problem?

Would be happy about any suggestion.


XNA: Classes with Texture2D to be treated as one

Summarized problem:
I have an "animation" class that I can treat as a Texture2D field as needed. I do not want to inherit from the class or their parents. I'd rather not create a parent class of both the animation class and a "container" for a Texture2D, though this is the only way to accomplish what I want.

Context: https://pastebin.com/PTgJuYEU
It's an extremely simple class that can change. His goal is to use a Texture2D for the external processing of spreadsheets and so on. It is used in an ECS, but probably not as a component as I have it now.

For example, I would like to use it as a character for a Texture2D in Draw calls (this can be done with the & # 39; texture & #;; property) and also be kept in the same field and converted to it Treat it again as an animation class , (If anyone thinks there is a much better implementation, please let me know.)

Thank you in advance.

EDIT: If there is a way, I could make something perfect:
spriteBatch.Draw (Anim as Texture2D, Vector2.Zero, Color.White);

xna – Simplify Mathecode for Matrix – Sun Billboarding

When trying to set the correct position of my Sun billboard in my 3D game. I tried a long time to get it working right, but I wonder why this code has to be so complicated:

sun.sprite.Position = Vector3.Transform (Vector3.Transform (-sun.lightDir,
Quaternion.Inverse (world.Rotation)), Quaternion.Inverse (myRelativeRotation));

Can I simplify this expression? At least I tried to change it:

sun.sprite.Position = Vector3.Transform (-sun.lightDir,
Quaternion.Inverse (world.Rotation) * Quaternion.Inverse (myRelativeRotation)) 

However, this leads to different results, so that the sun is in the wrong place.

c # – XNA 4.0 To combine triangular vertices in 3D

Preview for the problem:

I'm doing a similar game to Minecraft (a game where the world is made up of dice), but the fps of the game are getting low only by rendering a small number of dice in the world.

So I decided to use the Combine / Margin technique to improve it. I want to combine cubes that are of the same type and whose positions are next to each other.

Suppose I have 4 faces of cubes juxtaposed in this order:

[+] [+]

[+] [+]

Right now: I rendered each face with 2 triangles so that I render all faces with 8 triangles.

Improvement that I would like to make: I want to render these surfaces with only two triangles, but keep the textures where they are. This means that you only use 2 tringles for 2 faces and 4 for this area.

Outside the topic:

Currently I use:

  • Frustum wheezing
  • Cube faces that lie on top of each other are not rendered.

Which fps improvement techniques do you recommend to use?
At the moment I only make 1500 faces at the same time [3000 triangles] My game reaches about 25 ~ fps.

xna – Trying to get vertex shaders to work with Monogame 2D

If I do not use the vertex shader, white textures appear. This is the default color. After adding the vertex shader, the screen is black.

I think there is something wrong with the matrices I give to the shader, but I'm not sure.

                #if OPENGL
#define VS_SHADERMODEL vs_3_0
#define PS_SHADERMODEL ps_3_0
#define VS_SHADERMODEL vs_4_0_level_9_1
#define PS_SHADERMODEL ps_4_0_level_9_1

Matrix WorldViewProjection;

struct VertexShaderInput
float4 position: SV_POSITION;
float4 color: COLOR0;
float2 texCoord: TEXCOORD0;

struct VertexShaderOutput
float4 position: SV_POSITION;
float4 color: COLOR0;
float2 texCoord: TEXCOORD0;

VertexShaderOutput MainVS (in the input "VertexShaderInput")
VertexShaderOutput output = (VertexShaderOutput) 0;

output.Position = mul (input.Position, WorldViewProjection);
output.Color = input.Color;

Return the output;

float4 MainPS (input VertexShaderOutput): COLOR
Return input. Color;

Technique BasicColorDrawing
Pass P0
VertexShader = Compile VS_SHADERMODEL MainVS ();
PixelShader = PS_SHADERMODEL Compile MainPS ();

My projection matrix (The default that uses sprite batch).

Projection = Matrix.CreateTranslation (-0.5f, -0.5f, 0) * Matrix.CreateOrthographicOffCenter (0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0, 0, -1)

Setting my WorldViewProjection matrix.

negEffect.Parameters["WorldViewProjection"].SetValue (projection);

Just the projection because I turned off my camera to make debugging easier.

The drawing code.

GraphicsDevice.SetRenderTarget (renderTarget);
GraphicsDevice.Clear (Color.Black);
var debugMatrix = debugCamera.GetViewMatrix ();

spriteBatch.Begin (SpriteSortMode.FrontToBack, BlendState.AlphaBlend, SamplerState.LinearClamp, null, null, negEffect);

spaceObjectManager.Draw (spriteBatch);
spaceEnemyManager.Draw (spriteBatch);
playerShip.projectileManager.Draw (spriteBatch);
playerShip.Draw (spriteBatch);

spriteBatch.End ();

GraphicsDevice.SetRenderTarget (null);

spriteBatch.Begin (SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone, null);
spriteBatch.Draw (renderTarget, new Rectangle (0, 0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height), Color.White);
spriteBatch.End ();

physicsDebug.RenderDebugData (ref SimProjection, ref debugMatrix);

VertexShader off.

VertexShader off

VertexShader on.

VertexShader on

Thank you in advance!