FAQ Database Discussion Community


4 Vector2 points to top left top right bottom left bottom right

c#,xna
I have 4 Vector2 in a list and I want to sort them to Vector2 topleft Vector2 topright Vector2 bottomleft Vector2 bottomright I have tried by comparing the distance but had no success. I would like a fast way that solves my problem...

XNA 2d Camera not drawing

c#,camera,xna,xna-4.0
I am trying to implement a Camera class in XNA http://www.dreamincode.net/forums/topic/237979-2d-camera-in-xna/ It's not throwing up any errors when I try it, it simply doesn't draw anything inside it's targeted spritebatch. Tried making gigantic sprites or moving them around, to see if it was just placing them somewhere random. With no...

Why is XNA Write/ReadObject() not preserving Vertex/Index Buffer data?

c#,xna,xna-4.0
I'm building some custom content types with the XNA 4.0 content pipeline. I have a custom ContentTypeWriter and ContentTypeReader for my classes TerrainModelSetContent and TerrainModelSet respectively, which are each the build time and run time classes. A terrain model set of course includes/is a collection of models used for the...

Close XNA game window on rectangle click

c#,xna
I'm new to XNA and I'm trying to create a simple game menu and I'm using rectangles as menu items. I have the main class which is called Game1.cs and a different class for a rectangle, that is supposed to close the game on click, which is called _exitGame.cs. So...

Draw segments of circle on xna

c#,xna
How do I draw a circle sector (as in a slice of pizza shape) in xna? I'd like to use one as a timer indicator, so would like to be able change its angle dynamically. In an ideal world I'm looking for something like this: Drawsector (float startAngle, float endAngle,...

Syntax to call generic C# method from NLua

c#,generics,lua,xna,nlua
I'm having some trouble figuring out the correct syntax for calling a generic C# function from Lua with NLua. I'm trying to call the following C# XNA function from Lua GameWorld.Instance.Content.Load<Texture2D>("player"); But I'm having some syntax trouble with the generic <T> part. My current lua call looks like this, which...

Why is Loadcontent already executed inside Initialize() method?

c#,xna
I am trying out XNA / Monogame in Visual Studio. I find the documentation somewhat lacking in explaining how the main XNA structure operates. As I understand it, Game1.Initialize() gets called before Game1.LoadContent(). But in this code example, I have found that the Content actually IS already loaded when still...

Stop 3D objects moving when windows is resized [XNA/WinForms/C#]

c#,winforms,3d,xna,projection
I have an XNA windows inside a a windows form, and I am running into a problem when I resize the window. The behaviour I want is for the rendered cube to not move at all. So if there was a second cube offscreen to the right, and the user...

Adding Thumbstick Input to a Queue in XNA

c#,input,xna
I'm trying to store the user's most recent controller inputs in a queue, using XNA's GamePadStates. The way I'm attempting to do this is by getting the GamePadState in the current frame, comparing it to the state in the previous frame, converting all button presses and thumbstick inputs to characters,...

2D Monogame: Rectangle collision detection, side specific

c#,xna,monogame
I have two rectangles, one player, one map. The player needs to not be able to walk through the map. Both the player and map have a rectangle with position and texture width and height, both also have a Vector position. Rectangle.Intersect() only outputs a boolean value, I cannot figure...

XNA Game with MonoGame on Mac

osx,xna,monogame
I have just moved over to a mac and I am continuing my development with XNA using monogame. However when I am trying to use Gamepad.GetState(index) and it is throwing the following error. System.IO.FileNotFoundException: Could not load file or assembly 'Tao.Sdl, Version=1.2.13.0, Culture=neutral, PublicKeyToken=9c7a200e36c0094e' or one of its dependencies. at...

Which is better programming practice - Unnecessary parameters or a static variable?

c#,parameters,constructor,static,xna
I am making a game in C# and XNA 4.0 and one of my classes requires its own texture. The class is currently being used like this: Class constructor: class Item : ItemBase //It uses a base class { public Item(Texture2D myTexture) : base(myTexure) { } } New instance: Texture2D...

Limiting List Iterations in a For Loop (Closest To Player)

c#,optimization,xna,collision
I have a List<Collider> colliders which is for a tile map. One approach that I thought of is to check the full list for all colliders' positions, compare to player's position, then add closest colliders to a temporary list for faster iteration. Only doing this once every 100ms would decrease...

C# Console application dying when ran with .exe file

c#,xna,console-application
I'm making a game in XNA, and it's a multiplayer game, consisting of two solutions: One is the XNA Game, and another is the server done in C# console application. The server uses a reference to Microsoft.Xna.Framework When I run the server through VS13, it runs just as expected. But...

XNA - Reconnecting Content Project

visual-studio-2010,crash,xna,xna-4.0
I'm working with XNA 4 in VS2010. Recently a crash corrupted a .contentproj file of mine. So I deleted the content project inside VS, created a new one and repopulated it with the contents of the old one. However the new content project did not properly hook up to the...

Monogame XNA transform matrix for a single object?

c#,matrix,xna,monogame
I have read a few tutorials explaining transform matrices for XNA/Monogame. The problem is that these matrices are applied to SpriteBatch.Begin(...matrix); This means that all Draw code will be transformed. How do I apply a transformation matrix to a single drawable object? In my case I want to transform a...

Most efficient way to handle large arrays of data in C#?

c#,arrays,xna
Currently I am using XNA Game Studio 4.0 with C# Visual Studio 2010. I want to use a versatile method for handling triangles. I am using a preset array of VertexPositionColor items passed through the GraphicsDevice.DrawUserPrimitives() method, which only handles arrays. Because arrays are fixed, but I wanted to have...

Score not changing when collision occurs

c#,xna
I have been trying to get my score to work correctly when the player collides with one of the collectibles but the score does not seem to change when the collision occurs, I am not sure why this is happening. In my collectible I have this: class BlueBall : Obj...

Cutting a string at specified lengths

c#,arrays,string,xna
I've got an array that holds strings, and I wanted to know how I could take a string and cut a part off at a specified pixel length and add it into the array. For Example, string[] string1 = { "Hello World" }; I'm using XNA so I can get...

Optimization: Set or Subtract?

c#,optimization,xna
a very simple question here. I'm coding a multi-player game in XNA, what would be a better option here - and why? (Line 7 is the only changed line in each option) Option 1: const float SyncFrequency = (1 / 30f); float Sync; void Sync(GameTime GT) { Sync += (float)GT.ElapsedGameTime.TotalSeconds;...

Xamarin using cross platform 3D engine

xamarin,xna,cross-platform,monogame
I am a iOS / Android developer who has started to look at Xamarin for Business apps. As a hobby I make the odd 3D game and one thing thats always got me is having to write it for 2 platforms (Yes I do know about Unity, not my bag)...

How do I scale the graphics of a game?

c#,matrix,xna,window,scale
I'm making a game in C# and XNA 4.0. It's pretty much finished, but now I want to add settings so that players can change the window size if they want to. The current setup goes like this: void Initialize() { //The window size is initally 800x480 graphics.PreferredBackBufferWidth = 800;...

how do i use a property { get; }?

c#,visual-studio-2013,xna
I noticed that in the Microsoft.Xna.Framework.Rectangle struct, there are plenty of properties that are just public int Bottom { get; } or public Point Center { get; }. I, for the life of me, can't figure out what's going on here. I've tried replicating this in some of my own...

Can you use too many new instances in C# to cause memory issues?

c#,memory,xna,instance
I'm creating a game in C# and XNA 4.0. It consists of multiple levels with a player character, enemies, things to collect, etc. The levels are created using a Level class similar to the following. List<Level> levels = new List<Level>(20); //This is a list to hold all of the levels...

How to abstract/remove redundent methods in the following class sample

c#,inheritance,xna,abstraction
I'm trying to remove the redundancy I have in my Enemy0, Enemy1, ... classes that inherit from my abstract Enemy class. This is all Monogame/XNA. My abstract class looks like so: public abstract class Enemy { public abstract Vector2 Position { get; } public Enemy() {} public abstract void Update(GameTime...

How do I apply multiple matrices in spriteBatch.Draw()?

c#,matrix,xna
I'm making a game in C# and XNA 4.0. In some levels I need a camera matrix to make the level appear to scroll left/right. Additionally, I also need a scaling matrix to scale the graphics when the settings are used to change the window size. Both of my matrices...

When I pass a Texture2D as parameter to a class, this texture is null

c#,menu,xna,monogame
here is the code where I get the problem : namespace Menu_test { /// <summary> /// The main menu screen is the first thing displayed when the game starts up. /// </summary> class MainMenuScreen : MenuScreen { #region Initialization ContentManager content; Texture2D playgame; Texture2D exit; /// <summary> /// Constructor fills...

Loading Texture2D Inconsistently Fails

c#,xna,loading,texture2d
Sometimes (not always, most times it works flawlessly), I catch the exception I provided when it fails to load a Texture2D. public static class Extras { public static class Load { private static Dictionary<string, Texture2D> Textures; public static Texture2D Texture(string Path) { if (Textures == null) Textures = new Dictionary<string,...

Draw effect XNA with multiple texture

c#,xna,hlsl
In Xna I would like to draw my model with a custom effect.. SO I would like to get the textures from the mesh. foreach (ModelMesh mesh in model.Meshes) { foreach (ModelMeshPart part in mesh.MeshParts) { effect.Parameters["World"].SetValue(World ); effect.Parameters["View"].SetValue(View); effect.Parameters["Projection"].SetValue(Projection); effect.Parameters["TextureEnabled"].SetValue(true); var basicEffect = part.Effect as BasicEffect; if (basicEffect !=...

Cross Viewport oclussion culling

xna,overlay,viewport,xna-4.0,occlusion-culling
I'm currently working on a XNA project where I need to create a Picture in picture Overlay to displaying a 3D scene from multiple angles. currently I'm trying to use 2 viewports to do this. The main one fills whole screen and is working as desired. The second is placed...

XNA tilemap tileset

c#,xna,tile
I'm making a 2d sidescrolling game and im trying to use a 2dimensional or so-to-say tileset. My friend gave me some code that he had been using for his games but his code only supports 1 dimension. public void DrawMap(Texture2D tilesheet, SpriteBatch spriteBatch) { for (int x = 0; x...

Trying to build JSIL gives 47 errors

c#,visual-studio-2012,xna,jsil
I am trying to build the JSIL project. I already have a XNA game which I want to convert to use in a webbrowser via JSIL. I've followed up all the instructions on the JSIL wiki. Yet it gives me 47 errors when I try to build the project. I...

XNA costing/easing between positions

c#,xna,trigonometry
Game overview: 2D World, player and camera are separate I'm attempting to make a game where the camera follows the player and follows the median route (so moving x+ then x- quickly results in little camera movement) and I've got it so the camera has its own acceleration but I'm...

How to “cast” an Object

c#,arrays,object,xna
I have a function that receives an array of Objects. I also have a class called Rectangle but when I iterate the array of objects I need the Object in that index to be casted as Rectangle and not as object because the function I will use needs the parameter...

“Object reference not set to an instance of an object” [duplicate]

c#,xna,nullreferenceexception
This question already has an answer here: What is a NullReferenceException and how do I fix it? 17 answers public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; //Character Texture2D character; Texture2D background; Texture2D ground; //Movement Vector2 position = Vector2.Zero; Vector2 velocity; bool hasJumped; float movespeed = 500f;...

Remembering a direction, moving to a point, then changing direction. XNA

c#,xna,movement,pacman
I'm making a pacman clone in XNA. So far I've drawn the tile map using 2D array, added the pills using another 2D array and made a 2D array that allows movement of pacman. In the actual game you can press right whilst moving up, and it will wait until...

How to check if Mouse is available in XNA - Monogame

c#,xna,mouse,monogame,win-universal-app
I'm using Monogame to develop an universal app for Windows Store and Windows Phone. I know that is possible to check if a TouchPanel is available and I'm looking for a method that do the same thing with a mouse. I can't ignore the fact that a mouse is not...

I can't fix camera to any object in a 2D Matrix

c#,matrix,camera,xna,viewport
Problem description: I am trying to develop some 2D game with terrain collision in C# using XNA framework. I have already completed simple terrain generating and object, for example car, can move on this terrain. But now, I get a problem with camera fix to that car. I tried to...

How I can close XNA application before the Form? C#

c#,xna
I'm doing XNA application. I use Game1.cs (XNA file) and MainForm.cs (form file) Program.cs MainForm mainForm = new MainForm(); mainForm.Show(); Game1 game = new Game1(mainForm); game.Run(); When "X" button is clicked I try to close all application in MainForm.cs private void MainForm_FormClosed(object sender, FormClosedEventArgs e) { Application.Exit(); } Unfortunally, Game1.cs...

XML serialization of derived class in a list, need to set member on parent class

c#,xml,serialization,xna,xml-serialization
As a hobby, I'm making a 2D RPG in XNA and C#. I have a class called ObjectiveData. Its only member is a string called objectiveID. Derived from this are various other classes (GatherItemsObjectiveData, SpeakToNPCObjectiveData, etc) - all of them are suppose to store their own objective data related to...

keeping output after key is released c# XNA

c#,arrays,string,xna
I am currently working on a "Player Select" screen for a Beat em' up. I have an array of six strings (player one, player two...). The players current choice is highlighted and when they press the enter key I want a sub menu to appear giving them the option to...

how to convert type 'string' to 'string[]' in c#?

c#,xna
i have a bit of a problem with my code please can you help: String[] Boe; Boe = new String[1]; <---- i think the error might also be here BS = new Rectangle(); for (int p = 0; p < 1; p++) { //some code have been taken out Boe...

Toggleable pause screen XNA 4.0 C#

c#,visual-studio-2010,xna
I am making a simple game in C# using the XNA 4.0 framework but am having problems implementing a pause feature. I want it to start off paused then, upon hitting the P key unpause and start gameplay, then at any time when P is pressed, pause it again. So...

XNA : 2D Foreach Collision detection issues with a reference of “t” not exiting in current context.

c#,foreach,xna,collision
My problem is that; when doing collision detection using bounding boxes my second player's arrows are not detecting the fact that they are hitting the "pots" on screen. My first player can hit them just fine, when trying to duplicate the player 1's foreach statement for detecting collisions I have...

How do I make the code Wait for a few milliseconds in C#?

c#,xna,collision,game-physics
I have made some collision if statements, but they didn't work. birdbox3.X += 5; birdbox3.Y -= 5; if (birdbox3.Intersects(Banner1)) { birdbox3.Y += 10; } else if (birdbox3.Intersects(Banner2)) { birdbox3.Y = -birdbox3.Y; } So if we take the first statement, the box is initially on the left down corner. According to...

I need to make an AI character that follows the player when they reach a certain distance in C# XNA

c#,xna,artificial-intelligence,path-finding
Here is the code that I have so far for my game. I am wanting to create an AI character (BlackBall) that will follow the player (WhiteBall) when they are a certain distance away. I have no idea where to start to get this working but it will be a...

Getting a vector from an angle and length?

c#,vector,xna
I'm working on a monster's sight(cone-shaped) and need a way to draw it. The vector I get from the angle/distance will be centered around a position(the monster's position). Using C#/Xna, how can I get a vector if I have an angle and distance(length from position)? The answer helped lead me...

Artificial intelligence (or at least path generation) of entities in a 2-dimensional plane

c#,xna,artificial-intelligence,2d-games
TL;DR Given a 2-dimensional plane (say, 800x600 pixels or even 4000x4000) that can contain obstacles (static objects) or entities (like tanks, or vehicles), how can computer-controlled tanks navigate the map without colliding with static objects while pursuing other tanks? Please note that every static object or entity has the ability...

How to modulo a number once?

c#,xna,modulo
This is my first question, so sorry if it is badly worded. I'm working in C# and XNA and came across an issue. When collecting the score it does it in increments of 9, and I would like it to increase in increments of 1, so I developed this: float...

Detecting multiple key presses in C# and XNA 4.0

c#,keyboard,xna,state
I want to detect if a specific set of keyboard keys are being held down at once in C# and XNA 4.0. I'm doing so with the following code: KeyboardState keyState = Keyboard.GetState(); if(keyState.IsKeyDown(Keys.S) && keyState.IsKeyDown(Keys.K) && keyState.IsKeyDown(Keys.I)) { //Do something } This code detects if the user is pressing...

Returning type based on non-compile time variables

c#,xna
I'll start off by saying that I don't know if this is the most optimal method of loading resources, but right now my resource manager has content submitted to it at LoadContent, then flushes its resources and stores them in a list. Then At any point in the game's code...

How can I shrink my large texture so that it stays centered?

c#,xna,texture2d
When I shrink my large texture down, it doesn't shrink the image. It just cuts off the image starting from the bottom right and going up diagonally. This is how I am drawing the sprite: spriteBatch.Draw(Tiles[0].TileTexture, new Vector2(x * TileWidth, y * TileHeight), Color.White); This is the base image I'm...

XNA animation inside WPF

c#,wpf,animation,xna,xna-4.0
My question is it possible to do play XNA animation inside WPF ? and how can I achieve this ? I did little searching and found that it's possible with Winform but I need to do it in WPF as my whole project is in wpf and only this issue...

XNA Diagonal Movement Key Release

c#,xna,game-physics,movement
Ok, so say you're playing a top down game. You press W and D to go in the up-right direction. Now you just want to go right, so you release the W key. One would expect you to then change directions and head right, but instead, you continue up-right. What...

Function of base.Update and base.Draw in Monogame?

c#,xna,monogame
I am following the basic Monogame tutorial from this website. What I can't figure out is why Game1.cs includes calls to base.Update and base.Draw? If I remove these function calls, it does not seem to affect my game in any way... Code Game1.cs protected override void Update (GameTime gameTime) {...

C# XNA Array Removal

c#,arrays,methods,xna
I'm trying to make a simple brick breaker game. I have everything created with collision and simple physics. The ball bounces off the paddle and walls, but I'm having trouble with the bricks. I can get the ball to bounce off the bricks, I'm just not experienced enough to know...

Invisible geometry in DX11

xna,alignment,directx,directx-11,xna-math-library
After struggling for many hours to understand and compensate for Microsoft's deprecation of D3DX in Windows 8, I've run into a problem that I can't shake off. The first time I started my program, it became immortal because of an access violation. After having restarted my computer and recompiling and...

XNA - Input string was not in correct format

c#,xna
For my load method, where I read in the sprites positions. When I run the game and Press 'L' to load, it says "Input message was not in correct format". This is my whole code: using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using...

How do I make a texture rotate to face a Vector2?

c#,rotation,xna
I'm making a game in C# XNA 4.0 and I want the game to have guns that rotate to face the player and shoot at them. I have attached a picture below to summarise this. I have the shooting AI implemented, but I want to know how I can make...

In C# XNA, how do I display my sprites in random places every time the game loads?

c#,random,xna
I am having trouble with loading my sprites in random places when the game loads, I have currently got them set in specific positions as shown below: BlackBallRectangle = new Rectangle(150, 300, 25,25); BlackBallRectangle2 = new Rectangle(500, 400, 25, 25); BlueBallRectangle = new Rectangle(500, 150, 25, 25); GreenBallRectangle = new...