A way to store potentially infinite 2D map data? I have a 2D platformer that currently can handle chunks with 100 by 100 tiles, with the chunk coordinates are stored as longs, so this is the only limit of maps (maxlong maxlong). All entity positions etc etc are chunk relevant and so there is no limit there. The problem I'm having is how to store and access these chunks without having thousands of files. Any ideas for a preferably quick amp low HD cost archive format that doesn't need to open everything at once?


In XNA, should I use the built in game component classes? I'm just getting started on an XNA game for Window Phone 7. For my Flash games I have my own framework that I was just going to port from AS3, but I have just found the built in game component stuff in XNA. So should I use this stuff? Should my Entity class extend game component drawable game component? I'm sure it will be quicker just to port my AS3 code, but I thought this built in stuff may have some advantages? UPDATE I decided not to use them. It doesn't seem that they are meant to be used in the way I described.


Percentages for different platform generation I have a level manager, which creates levels and levels create platforms. Levels can contain a variety of platforms. I dont really understand how I can say I want a 10 of one platform being made, 30 chance of another, and 70 chance for anotgher and so on... At the moment I have a method that looks like this private void creationManager(float moveChance, float breakableChance, float superJumpChance) I'm not sure how I can use these values and probabaility to determine which type of paltform is created. Any ideas?


Can someone explain to me the difference between 2 XNA methods? I was recently trying to make a boucing ball off the environment walls. I apparently had everything correct, except for one thing, that I corrected stupidly, which made my code work, but I don't understand why. So I had set the value of a 2d vector's X and Y inside protected override void Update(GameTime gameTime) this vector was what I would add to the object's X and Y so it could move according to whatever logic. But it didn't work, the fix to this problem was to apparently declare the vector's values inside protected override void LoadContent(). So can anyone explain to me, what is the difference between declaring your variables constants inside these two methods? And why? EDIT Wrong Sourcecode protected override void LoadContent() Create a new SpriteBatch, which can be used to draw textures. spriteBatch new SpriteBatch(GraphicsDevice) Loaded content protected override void Update(GameTime gameTime) Allows the game to exit if (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Escape)) this.Exit() Code logic movement.X 5 movement.Y 5 birdbox3.X (int)movement.X this variable was declared outside of any local field as a rectangle if (birdbox3.X lt 0) movement.X movement.X else if (birdbox3.Y lt 0) movement.Y movement.X base.Update(gameTime) So when I would run this code, the birdbox3 would just stop when the if statement is fulfilled. The correct version would be to cut the movement.X 5 movement.Y 5 and paste it into LoadContent() instead. The problem is I do not know why.


Windows Class Library vs XNA Class Library I'm going to start a library in C for Navigational Meshes. I would like to use it in both WPF Winforms and in XNA. Can I create a windows class library and still use it in XNA?


Whats the point of all these Surface Formats I am relevantly new to Graphics Programming. I have written some basic games in xna in the past but I am trying to understand what the point of all these surface formats is. For instance Xna and DDS support the standard RGBA (8bpp). Why does one need 32 bpp or even stranger combinations of bits per channel like Rg32. Isn't it enough to have the standard DXn, RGBA, and HDR formats?


What kind of performance issues does multiple instances of the exact same object have on a game? I'm fairly new to programming, and I've pretty much learned all the things I know on the go, while working on projects. The problem is that there some things that I just don't know where to begin searching. My question is about performance, and how can multiple instances of the same object affect it Specifically, I'm talking about XNA's "GraphicsDevice" class. I have it instanced on four different parts of my game, and in three of those, the object has the exact same values for all the attributes. So, in that case, should I be using the same instance of GraphicsDevice, passing it as a parameter, even if I use it in different classes? I apologize if the question seems redundant, but like I said, I've taught myself most of what I know, so there are quite a few "holes" in my learning process.


Isometric drawing "Not Tile Stuff" on isometric map? So I got my isometric renderer working, it can draw diamond or jagged maps...Then I want to move on...How do I draw characters objects on it in a optimal way? What Im doing now, as one can imagine, is traversing my grid(map) and drawing the tiles in a order so alpha blending works correctly. So, anything I draw in this map must be drawed at the same time the map is being drawn, with sucks a lot, screws your very modular map drawer, because now everything on the game (but the HUD) must be included on the drawer.. I was thinking whats the best approach to do this, comparing the position of all objects(not tile stuff) on the grid against the current tile being draw seems stupid, would it be better to add an id ON the grid(map)? this also seems terrible, because objects can move freely, not per tile steps (it can occupies 2 tiles if its between them, etc.) Dont know if matters, but my grid is 3D, so its not a plane with objects poping out, its a bunch of pilled cubes.


How to Create a New Instance of a Game Object Alright, please don't scald me here haha. I'm very new to XNA, C , and game development as a whole. I have done web design, but that is my main experience with programming. It is a Space Invaders type ish game. In the code below I have a Meteor class. In this class I want to create a meteor in a random location (on the X axis) and then have it fall. I don't care much about it doing damage yet. I can always get one meteor created, and falling, yet when I press 'M' to create another instance of the class it isn't creating another meteor. I could very possibly be going about this entirely wrong...please forgive me if I am. class Meteor private Random randomNumber new Random() private Rectangle position private int fallSpeed private double damage private int x, y 0 private int WIDTH, HEIGHT List to hold meteors created (holds instance of Meteor class) List lt Meteor gt meteors new List lt Meteor gt () Texture for the meteor private Texture2D meteor lt summary gt Create the meteor and each meteor's properties lt summary gt public Meteor() HEIGHT randomNumber.Next(0, 60) WIDTH HEIGHT fallSpeed randomNumber.Next(0, 10) damage fallSpeed 2 x randomNumber.Next(0, 600) Randomly generates where meteor will spawn on X axis public void createMeteor() meteors.Add(new Meteor()) lt summary gt Load content (graphics) relating to the meteor lt summary gt public void LoadContent(ContentManager Content) Load meteor texture meteor Content.Load lt Texture2D gt ("Sprites meteor") lt summary gt Update the meteors position lt summary gt public void Update() Update position of metoer (falling) y Testing purposes mostly...I want meteors to be created when I press 'M' if (Keyboard.GetState().IsKeyDown(Keys.M)) createMeteor() lt summary gt Draw the metoer (and it's new position). lt summary gt public void Draw(SpriteBatch spriteBatch) position new Rectangle(x, y, HEIGHT, WIDTH) spriteBatch.Draw(meteor, position, Color.White) So I can get the damage public double getDamage() return damage


How can I determine the contact point of a collision? I have two Farseer bodies. A static rectangle and a dynamic ball that is flying around. I want to determine where the ball touched the rectangle. I need the exact coordinates of the contact point. How can I do that? Is there a way to determine the contact point? bool BlueRectangle OnCollision(Fixture fixtureA, Fixture fixtureB, FarseerPhysics.Dynamics.Contacts.Contact contact) if (fixtureB.Body RedBall) Vector2 normal FixedArray2 lt Vector2 gt worldPoints contact.GetWorldManifold(out normal, out worldPoints) if(contact.Manifold.PointCount gt 1) Vector2 contactPoint worldPoints 0 return true It works with the following code.


Error instantiating Texture2D in MonoGame for Windows 8 Metro Apps I have an game which builds for WindowsGL and Windows8. The WindowsGL works fine, but the Windows8 build throws an error when trying to instantiate a new Texture2D. The Code var texture new Texture2D(CurrentGame.SpriteBatch.GraphicsDevice, width, 1) Error thrown here... texture.setData(FunctionThatReturnsColors()) You can find the rest of the code on Github. The Error SharpDX.SharpDXException was unhandled by user code HResult 2147024809 Message HRESULT 0x80070057 , Module Unknown , ApiCode Unknown Unknown , Message The parameter is incorrect. Source SharpDX StackTrace at SharpDX.Result.CheckError() at SharpDX.Direct3D11.Device.CreateTexture2D(Texture2DDescription amp descRef, DataBox initialDataRef, Texture2D texture2DOut) at SharpDX.Direct3D11.Texture2D..ctor(Device device, Texture2DDescription description) at Microsoft.Xna.Framework.Graphics.Texture2D..ctor(GraphicsDevice graphicsDevice, Int32 width, Int32 height, Boolean mipmap, SurfaceFormat format, Boolean renderTarget) at Microsoft.Xna.Framework.Graphics.Texture2D..ctor(GraphicsDevice graphicsDevice, Int32 width, Int32 height) at BrewmasterEngine.Graphics.Content.Gradient.CreateHorizontal(Int32 width, Color left, Color right) in c Projects Personal GitHub BrewmasterEngine BrewmasterEngine Graphics Content Gradient.cs line 16 at SampleGame.Menu.Widgets.GradientBackground.UpdateBounds(Object sender, EventArgs args) in c Projects Personal GitHub BrewmasterEngine SampleGame Menu Widgets GradientBackground.cs line 39 at SampleGame.Menu.Widgets.GradientBackground..ctor(Color start, Color stop, Int32 scrollamount, Single scrollspeed, Boolean horizontal) in c Projects Personal GitHub BrewmasterEngine SampleGame Menu Widgets GradientBackground.cs line 25 at SampleGame.Scenes.IntroScene.Load(Action done) in c Projects Personal GitHub BrewmasterEngine SampleGame Scenes IntroScene.cs line 23 at BrewmasterEngine.Scenes.Scene.LoadScene(Action 1 callback) in c Projects Personal GitHub BrewmasterEngine BrewmasterEngine Scenes Scene.cs line 89 at BrewmasterEngine.Scenes.SceneManager.Load(String sceneName, Action 1 callback) in c Projects Personal GitHub BrewmasterEngine BrewmasterEngine Scenes SceneManager.cs line 69 at BrewmasterEngine.Scenes.SceneManager.LoadDefaultScene(Action 1 callback) in c Projects Personal GitHub BrewmasterEngine BrewmasterEngine Scenes SceneManager.cs line 83 at BrewmasterEngine.Framework.Game2D.LoadContent() in c Projects Personal GitHub BrewmasterEngine BrewmasterEngine Framework Game2D.cs line 117 at Microsoft.Xna.Framework.Game.Initialize() at BrewmasterEngine.Framework.Game2D.Initialize() in c Projects Personal GitHub BrewmasterEngine BrewmasterEngine Framework Game2D.cs line 105 at Microsoft.Xna.Framework.Game.DoInitialize() at Microsoft.Xna.Framework.Game.Run(GameRunBehavior runBehavior) at Microsoft.Xna.Framework.Game.Run() at Microsoft.Xna.Framework.MetroFrameworkView 1.Run() InnerException Is this an error that needs to be solved in MonoGame, or is there something that I need to do differently in my engine and game?


How can I show xna graphics content in a control on a form in xna? I was able to create a form in xna using "Add Windows Form", named "Form1" then adding Application.EnableVisualStyles() Application.SetCompatibleTextRenderingDefault(false) Application.Run(new Form1()) How can I add graphics to some control, perhaps a picturebox, on Form1 that could potentially show my game as in a level editor? Thanks.


Overlapping Vertex in DynamicVertexBuffer draw priority? I am creating a voxel game, and I have recently run into an issue. My world is drawn by a DynamicVertexBuffer, which just consists of vertices for the blocks themselves. On top of that, I switch vertex buffers to my "Selected" vertex buffer which draws a white outline of a block for now. (This includes alpha but I have it turned off until I figure this glitch out). This issue I run into is here Rather than the selected buffer overwriting my world block, it sort of does depending on the angle. Sometimes I see no overlap, sometimes weird glitches like shown above. I was wondering, what can I do to prioritize the "Selected" buffer so that it is drawn on top of anything else sharing coordinates? Note that I did have this working, when everything used a basic effect. After switching to my own custom effect.fx (which supports fog and lighting, if that has anything to do with it), I run into this issue. Any help is appreciated, thank you! EDIT Just got the "flickering" of sorts to stop, I changed the DepthStencilState of the buffer to GraphicsDevice.DepthStencilState DepthStencilState.None The only downside here is that it draws all 6 sides of the selected block now and it overlaps the world completely, again I don't know if this would be the right way to do it but any help would be appreciated The above picture is flat with the rest of the terrain around it, as you can see it draws the two sides that wouldn't actually be visible as well.


Trouble with SAT style vector projection in C XNA Simply put I'm having a hard time working out how to work with XNA's Vector2 types while maintaining spatial considerations. I'm working with separating axis theorem and trying to project vectors onto an arbitrary axis to check if those projections overlap, but the severe lack of XNA specific help online combined with pseudo code everywhere that omits key parts of the algorithm, googling has left me little help. I'm aware of HOW to project a vector, but the way that I know of doing it involves the two vectors starting from the same point. Particularly here http www.metanetsoftware.com technique tutorialA.html So let's say I have a simple rectangle, and I store each of its corners in a list of Vector2s. How would I go about projecting that onto an arbitrary axis? The crux of my problem is that taking the dot product of say, a vector2 of (1, 0) and a vector2 of (50, 50) won't get me the dot product I'm looking for.. or will it? Because that (50, 50) won't be the vector of the polygon's vertex but from whatever XNA calculates. It's getting the calculation from the right starting point that's throwing me off. I'm sorry if this is unclear, but my brain is fried from trying to think about this. I need a better understanding of how XNA calculates Vector2s as actual vectors and not just as random points.


Is it possible to update the livetile in XNA WP7 game? ( I'm not sure if this question belongs here, but since it is related to game development and I have no idea where else I should post this, I will post this here ) As the title says, what I am basically asking is if it is possible to update the livetile of an pure XNA game ( not SL XNA hybrid )? I've been thinking something like that whenever user launches the game, I would create an texture dynamically and then update the livetile to show that texture. Even better would be if I could schedule this code to run for example once a day, without requiring user to even launch the game. Is this possible in WP7 or in WP8 ( is the WP8 SDK even publicly released yet? ) in pure XNA game? What about in XNA SL hybrid?


Shared Texture2D in XNA I am trying to define texture2d objects as shared. The reason of why I am trying to do is, I made an xna user control and my project loads unlimited (as much as the user wants) my XNA User Control. And all of the textures are same. I don't want to load textures for everyone of them (think how much ram size it will use if I do it) The real problem is cmMaps New ContentManager(Services, "Maps") As you see, ContentManager news ServiceProvider for initialization. When I look at the codes where Services variant modified, I see this lines GraphicsDeviceService GraphicsDeviceService.AddRef(Handle, ClientSize.Width, ClientSize.Height) m services.AddService(Of IGraphicsDeviceService)(GraphicsDeviceService) Why I can't define global Texture2D objects. Why is it specific for the window or control that the XNA tries to draw on? Is it possible to define em as shared variant and able to use it in every XNA UserControl? Note I took UserControl source codes from this page http xbox.create.msdn.com en US education catalog sample winforms series 1


how to create a Quaternion from an Orientation Vector in xna I have a Vector3 represents an Orientation in 3D , how to convert it to the corresponding Quaternion ? Is there any quick way ? EDIT I want to add an angular velocity vector to the Orientation Quaternion of the body


How to make HLSL effect just for lighting without texture mapping? I created an effect and just want to use lightning but in default effect that XNA create we should do texture mapping or the model appears 'RED', because of this lines of code in the effect file float4 PixelShaderFunction(VertexShaderOutput input) COLOR0 float4 output float4(1,0,0,1) return output If I want to see my model, I must do texture mapping by UV coordinates. But my model does not have UV coordinates assigned or its UV coordinates are not exported. I do texture mapping by this line of code in vertexshaderfunction output.UV input.UV When I use BasicEffect I have no problem and model appears correctly. How can I use "just" lightings in my custom effects? here is inside of my Model Using BasicEffect This is my code for drawing with or without BasicEffect inside of my draw() method Matrix baseWorld Matrix.CreateScale(Scale) Matrix.CreateFromYawPitchRoll(Rotation.Y, Rotation.X, Rotation.Z) Matrix.CreateTranslation(Position) foreach(ModelMesh mesh in Model.Meshes) Matrix localWorld ModelTransforms mesh.ParentBone.Index baseWorld foreach(ModelMeshPart part in mesh.MeshParts) Effect effect part.Effect if (effect is BasicEffect) ((BasicEffect)effect).World localWorld ((BasicEffect)effect).View View ((BasicEffect)effect).Projection Projection ((BasicEffect)effect).EnableDefaultLighting() else setEffectParameter(effect, "World", localWorld) setEffectParameter(effect, "View", View) setEffectParameter(effect, "Projection", Projection) setEffectParameter(effect, "CameraPosition", CameraPosition) mesh.Draw() setEffectParameter is another method that sets effect parameter if i use my custom effect.


XNA Vertex buffer Index buffer high memory usage? I've got about 120mb of vertex and indices data, but when I set the data in the vertex and indices buffer it ramps up to about 300mb of memory used, this isn't really acceptable and I don't know why it is, my code to set them is vertex buffer new VertexBuffer(device, VertexPositionColor.VertexDeclaration, chunk vertices.Count, BufferUsage.WriteOnly) vertex buffer.SetData(chunk vertices.ToArray()) index buffer new IndexBuffer(device, IndexElementSize.ThirtyTwoBits, chunk indices.Count, BufferUsage.WriteOnly) index buffer.SetData(chunk indices.ToArray())


How do I plot individual pixels using the XNA APIs? If I wanted to fill my game screen with individually coloured pixels, how would I do this? For example, if I wanted to write a 'game of life' type game where each pixel was a cell, how would I achieve this using XNA? I've tried just calling SetData() on a Texture2D object using a screen sized array of Color values, but it complains with You may not call SetData on a resource while it is actively set on the GraphicsDevice. Unset it from the device before calling SetData. How do I do as it asks? Or better still... is there an alternative, better, efficient way to fill a screen with arbitrary pixels?


Volume raycaster problems HLSL I can't seem to get my volume raycaster to work properly. I've been poking around changing things for days trying to get it to display my volume correctly but I seem only to get distorted mutations of it. What I tried to do was a 1 pass renderer because the 2 pass one I made wasn't good enough for my purposes. I'm using C XNA and the renderer wont have to handle transparency so it only has to get in and fetch the first color it bumps into. How it should look How it looks float4 OnePassPS(OnePassVSOutput input, float2 pixelCoord VPOS) COLOR0 float3 rayDir normalize(mul(float3(((pixelCoord WindowSize) 2) 1.0, FocalLength), ModelView)) float4 pos float4(RayOrigin (rayDir (input.pos.z input.pos.w)), 0) float3 Step rayDir StepSize float4 color float4(0, 0, 0, 0) for(int i 0 i lt Iterations i ) color tex3Dlod(VolumeS, pos) if(color.a gt 0) break pos.xyz Step return color


XNA HLSL Shader Glow I have googled this to death, and I still don't quite understand it. I'm trying to create a glow effect in XNA using HLSL. A long time ago I was able to do it the way most people suggest which is by sampling the pixels from a texture, however I've always been curious about how you can make it more advanced so that you could do things like set the glow distance and stuff. If I recall from back when I was creating something like this in a similar project, there was always a limit as to how much I could sample before the computer couldn't handle it, hence limiting the glow distance. I wanted to know if there was a more sophisticated way of doing it, one that would have no glow distance limit? And I'm not referring to lighting ground textures either, the idea I have in my head is to have a set of vertices that all join together to create a LineList (for this example lets say they create a cube), so you have very thin lines creating a shape, and then you can set a glow on this object that has no limit to its distance, kinda like how Photoshop works I guess. Thanks


Am I hurting myself by not knowing C for game design? Right now, I feel I am strong in both Java a C . (Not much of a leap from one to the other really). While I don't expect a game designer programmer is an attainable goal early on in my career, This is a goal I will reach later on in my career. With this in mind, I feel that ignoring C and game design tools associated with it are eventually going to hurt me or slow me down in my ability to reach my goal. Is this the case? Or can I continue to hone my C skills using XNA and WPF for personal projects that can elevate me into such a career?


How should the actual game interface with the menu system I'm using the Game State Management (GSM) concept in my prototype and I like it very much. One of the screen has a "Game" embeded in it, where all the "good stuff" happens. The menu launching the game works fine, but I'm not sure how I should allow the game to request a screen from the ScreenManager. I'm not talking about a menu screen, but about something contextual to the game. For clarity's sake, let's say that when I click on a game element (a rendered model for example) I want a screen that asks me what color I want that model to be drawn next. Right now, my game knows that model is "targeted" with the mouse (I use a Ray picking approach). I looked at the Role Playing sample to see how they did this, but when their GameScreen handles the keys, to open the inventory for example, it's never contextual to what's actually happening in the GameScreen. Ideas welcomed! Edit The game must also be able to get a feedback or something from the "contextual screen" to get the new model color, for example.


How can I skew my XNA sprites? I would like to make a 2D tile based game, but, to make it look a bit prettier, I would need to skew textures so that it would look more like a 2.5D game. So I thought maybe I should skew textures to something like this So far I only found one topic about it http forums.create.msdn.com forums p 37143 215098.aspx 215098 But I don't really understand it. Maybe some of you do, can tell me how to skew my sprites?


FPS Camera Look Direction I'm using XNA to create an FPS camera that uses a Direction vector instead of a Target vector control the camera's orientation. I'm having trouble with the math for looking up and down when the camera is rotated about the Y axis. No problems looking left and right. Here's my code Vector3 LookDirection get set public void LookLeft(float scale) LookDirection Vector3.Transform(LookDirection, Matrix.CreateRotationY(MathHelper.ToRadians(scale))) public void LookRight(float scale) LookDirection Vector3.Transform(LookDirection, Matrix.CreateRotationY(MathHelper.ToRadians( scale))) public void LookUp(float scale) doesn't work when camera is rotated into the X axis LookDirection Vector3.Transform(LookDirection, Matrix.CreateRotationZ(MathHelper.ToRadians(scale))) public void LookDown(float scale) doesn't work when camera is rotated into the X axis LookDirection Vector3.Transform(LookDirection, Matrix.CreateRotationZ(MathHelper.ToRadians( scale))) I know I need to manipulate both the X and Z components when looking up and down, I just can't figure out exactly what to do. Thanks


Gap in parallaxing background loop The bug here is that my background kind of offset a bit itself from where it should draw and so I have this line. I have some troubles understanding why I get this bug when I set a speed that is different then 1,2,4,8,16,... In main class I set the speed depending on the player speed bgSpeed (int)playerMoveSpeed.X 10 and here's my background class class ParallaxingBackground Texture2D texture Vector2 positions public int Speed get set public void Initialize(ContentManager content, String texturePath, int screenWidth, int speed) texture content.Load lt Texture2D gt (texturePath) this.Speed speed positions new Vector2 screenWidth texture.Width 2 for (int i 0 i lt positions.Length i ) positions i new Vector2(i texture.Width, 0) public void Update() for (int i 0 i lt positions.Length i ) positions i .X Speed if (Speed lt 0) if (positions i .X lt texture.Width) positions i .X texture.Width (positions.Length 1) else if (positions i .X gt texture.Width (positions.Length 1)) positions i .X texture.Width public void Draw(SpriteBatch spriteBatch) for (int i 0 i lt positions.Length i ) spriteBatch.Draw(texture, positions i , Color.White)


How to convert screen space into 3D world space? I am trying to make a 3D model to look at the mouse position. Currently I have this code MouseState mouseState Mouse.GetState() Matrix world Matrix.CreateTranslation(0, 0, 0) Vector3 source new Vector3((float) mouseState.X, 1f, (float) mouseState.Y) Vector3 mousePoint GraphicsDevice.Viewport.Unproject(source, this.game.Camera.Projection, this.game.Camera.View, world) System.Console.Out.WriteLine("x " mousePoint.X ", Y " mousePoint.Y ", Z " mousePoint.Z) I get output such as this in the console x 0.1787011, Y 999.7204, Z 299.7723 x 0.08917224, Y 999.8602, Z 299.8862 x 0.05908892, Y 999.9069, Z 299.9241 x 0.04422692, Y 999.9302, Z 299.9431 x 0.03303542, Y 999.9477, Z 299.9573 x 0.03109217, Y 999.9508, Z 299.9598 x 0.02930491, Y 999.9535, Z 299.9621 x 0.02770578, Y 999.9559, Z 299.9641 x 0.0263205, Y 999.9581, Z 299.9659 The player is positioned at Vector3.Zero. The camera is positioned at new Vector3(0.0f, 1000.0f, 300.0f). I would like to get output such as X 300, Y 0, Z 300 when moving the mouse to screen top left and when moving the mouse to screen center where the model is located I want to have X 0, Y 0, Z 0. So I want the world coordinates of the mouse so that I can make the player rotate towards the mouse. Basically I want to map mouse X into world X, mouse Y to world Z and the world Y coordinate can be 0 at all times.


Animated dice framework for XNA? I'm looking for a reusable 3d animated dice component I can reuse in my XNA board game. I know it might be wishful thinking in hoping such a component exists, but at the same time worthwhile checking. I'm looking for something that can give a realistic dice animation and return the dice result that matches the animation. Does such a thing exist?


How do I find two points at an angle on opposite sides of a circle? With reference to my previous question I'm using micklh's answer, which works perfectly. However, it calculates the gradient based on two points, a starting point and an ending point. I want to change that such that I can give it a center point, an angle in degrees, and a length. If you look at the picture from the other question You can sort of discern where the center point is, the x,y of starting ending locations become the dots based on the length of the gradient. I assume I would have to Take the center location Apply the angle length Gives me my ending x,y Take the center location Calculate the reverse angle Apply the reverse angle length Gives me my starting x,y Plug these starting ending positions to the answer from the other question. Am I correct? How would I do those steps?


XNA transparent objects? I've working on a voxel like game like Minecraft, but I'm not sure how I should handle alpha. I've got the world split into chunks and I render each chunk, I have things like leaves which have alpha which is either on or off, but if you look through them you can only see other chunks which have already been rendered, here's a picture because I can't explain it. http i.imgur.com EIRLa.png It also works with leaves from the same chunk, for example if I'm looking through them from one direction to another then I can see the other leaves through the leaves, but if I'm looking the other way I get the same effect.


Rotate vector by matrix? If I have a Vector, say (1,1), how can I rotate it around the origin (0,0)? I'm working in XNA if that helps.


Physics for moving blocks I'm working on a 2D game for windows phone where the player moves blocks around to bounce a laser beams. I need to create some simple physics for moving the blocks. For the moment I have a simple collision class, telling me if two rectangles collide. But that's not enough because when I'm moving a block the rectangle rectangle function doesn't work. By Doesn't work i mean,I manage the collision but I don't how to stop the block mooving while the user sliding the block. The collision response for the block I want is if the user tries to slide it on another object, the block should slide up against the other object and not overlap. How would I go about implementing this functionality? Some code about how i impletement mooving block Currentposition Station.Position TouchPanelCapabilities touchCap TouchPanel.GetCapabilities() if (touchCap.IsConnected) TouchCollection touches TouchPanel.GetState() if (touches.Count gt 1) Vector2 PositionTouch touches 0 .Position for (int i 0 i lt ListDragObj.Count() i ) if (ListDragObj i .Shape.Contains((int)PositionTouch.X, (int)PositionTouch.Y)) ListDragObj i .selected true else ListDragObj i .selected false ListDragObj i .Update(PositionTouch)


Should I use one line per .wav or one scene per .wav for character speech? I'm building a game in XNA and I wanted to know how I would organize the character speech portions of the game. These would include both cutscenes and anything else where characters interact. I wanted to know if it would be more efficient to use sound file (.wav) per character line, such as SCENE 4 ENTERING THE CAVE PLAYER1 Wow, this is going great! One file called "04 PLAYER1 01.wav" PLAYER2 I know! A file called "04 PLAYER2 01.wav" PLAYER1 Let's get going! A file called "04 PLAYER1 02.wav" I wanted to know if that would be better opposed to SCENE 4 ENTERING THE CAVE PLAYER1 Wow, this is going great! PLAYER2 I know! One file called "scene 04.wav" PLAYER1 Let's get going! I am aware that by going with option 2, you'd probably save a bit more space because you have less files (but they might be larger) but it poses the problem of coordinating it all. I was thinking maybe XML for coordinating the speech and cutscenes, but am open to other suggestions. ) P.S. This not intended to be a "DIALOG TREE". These are actual models moving their lips in accordance with sound!


XNA 4.0 Refresh AudioEngine, WaveBank and Others Not Found I'm going through the Learning XNA 4.0 book, and unfortunately I installed XNA 4.0 refresh. All the code up until now has worked, with the exception of me needing to remove the Framework.Net and Framework.Storage. (As a side question, will this be problematic later?) The problem I'm having now is that in my Game1.cs file, I have imported all of the XNA.Framework libraries, and when I try and create instances of any of the following classes, an error pops up saying VisualStudio can't find them AudiEngine, WaveBank, SoundBank, and Cue. I have googled around for a while, and the only solution I saw was to import Microsoft.Xna.Framework.Xact, but this doesn't seem to exist for me. Any help is much appreciated, Thanks Peter.


SpriteBatch.Begin() causes everyting else to be drawn incorrectly I just added this spriteBatch.Begin() spriteBatch.End() to my app and was greatly confused by the fact that this causes pretty much everything else (all of my 3D objects, that is) to be drawn incorrectly. After the code above has executed, no Z buffering seems to take place, but instead objects are just drawn in the exace same order as I send them to the scene with the last object drawn being fully visible even while it is located behing other objects. It also screwes up the sampler state for my textures (which I can fix by setting a new SamplerState for the device). What is going on and how do I fix it?


RPG like hit points growth algorithms help I am currently making an XNA game in C . I want to increase health as the player level up. I am currently using this equation. MaxHealth Convert.ToInt32(100 Math.Pow(1.17, level 1)) Its fine before the first 20 levels, but afterwards the health starts to increase extremely fast Level 1 100 Hp. Level 20 1.975 Hp. Level 30 9.493 Hp. Level 40 45.630 Hp. Level 100 658.546.089 Hp. Level 109 Crash value too big for an integer. How should i create these growth algorithms, so that the growth of hit points pr. level, will increase slowly. This is just an example, if you know a better growth rate, I will be happy to know that too. level 2 Hp base health 60 (Base health 100) level 3 Hp base helath 60 120 level 4 Hp base helath 60 120 180. But the max health formular will run on every update tick, so all this should happen in the same calculation. Edit Thank you all for your input, I really appreciate it. But while away from the question, I found a solution myself. Thank you very much. The solution if (level lt 35) this.baseMaxHealth Convert.ToInt32((vitality 10) Math.Pow(level, 2) 4) else this.baseMaxHealth Convert.ToInt32((vitality (level 25)) Math.Pow(level, 2) 4) I added vitality as an upgrade you can spend skill points or something on EDIT 2 I improved the code a bit if (level lt 35) this.baseMaxHealth Convert.ToInt32((vitality 10) Math.Pow(level, 2) 4) else if (level gt 125) this.baseMaxHealth Convert.ToInt32((vitality 100) Math.Pow(level, 2) 4) else this.baseMaxHealth Convert.ToInt32((vitality (level 25)) Math.Pow(level, 2) 4)


Instancing with empty data, or varying vertex counts? I am new to game development, having only developed a few games before, in 2D space, but with 3D rendering. I have implemented instancing before, but this is only my 2nd time doing it. I have a question regarding instancing. To do instancing, I have a geometry buffer having a vertex declaration (for instance) 32 VertexPositionColor elements. This is because I have a few elements with 32 vertices in them. I am rendering all elements as linelists. However, there are some elements in the list that doesn't have 32 vertices. I would like to include these in the instancing render process too. So my final question is, what happens if I (for instance) fill out 8 of the vertices with their indexes, but then still send all the 32 vertices into the instancing shader? Is it possible? Is there a better approach to be able to instance all kinds of elements, with various vertex counts?


Texturing voxel faces separately I am creating a 3D level editor which should be used to generate the very basic layout (level geometry) and a few basic game logic entities of maps used in my game. So far, I decided to use voxels (i have a fbx untextured model file and do NOT draw this myself via vertices etc. as I already found tutorials on that which are not suitable for me) as the way to create the level geometry and most of this works fine. The next step would be to implement code that allows me to texturize these cubes by specifically applying textures to faces. Using something like the following Draw method I can apply a Texture2D to the whole voxel (so I am not able to chose the face to which I want to apply the texture) and this works fine for now (though I have sometime issues orienting it, which should not be part of this question) public void Draw() foreach(ModelMesh mesh in this.Model.Meshes) foreach(ModelMeshPart part in mesh.MeshParts) BasicEffect effect (BasicEffect)part.Effect effect.World this.World effect.View Engine.View effect.Projection Engine.Projection if(this.Texture ! null) UNLIT textures effect.Texture this.Texture effect.TextureEnabled true else LIT placeholder voxel effect.EnableDefaultLighting() mesh.Draw() I will have about 10 textures which I want to be able to apply programmatically on each face of the voxels which approach would you suggest me to achieve the desired result?


TypeLoadException when running a Monogame Windows Phone 8 game Using Monogame, I'm trying to port a game to Windows Phone 8, but I'm having issues getting a basic example to run. When I create a basic Mono project and run it on my phone (to check everything's OK), it compiles the game, and deploys it to my phone, but when the app starts running, the debugger throws this error I tried adding a reference of that .dll, but that doesn't solve it. This is the first time that I use Monogame, so please bear with me.


How can I implement collision detection for these tiles? I am wondering how this would be possible, if at all. In the image below The light brows tiles are ground, while the dark brown is background, so the player can pass over those tiles. Here's the for loops that draws the level float scale 1f for (row 0 row lt currentLevel.Rows row ) for (column 0 column lt currentLevel.Columns column ) Tile tile (Tile)currentLevel.GetTile(row, column) if (tile null) continue Texture2D texture tile.Texture spriteBatch.Draw(texture, new Microsoft.Xna.Framework.Rectangle( (int)(column currentLevel.CellSize.X scale), (int)(row currentLevel.CellSize.Y scale), (int)(currentLevel.CellSize.X scale), (int)(currentLevel.CellSize.Y scale)), Microsoft.Xna.Framework.Color.White) Here's what I have so far to determine where to create a Rectangle Microsoft.Xna.Framework.Rectangle ,,, groundBounds new Microsoft.Xna.Framework.Rectangle ?, ?, ?, ? int tileSize 20 int screenSizeInTiles 30 var tilePositions new System.Drawing.Point screenSizeInTiles, screenSizeInTiles for (int x 0 x lt screenSizeInTiles x ) for (int y 0 y lt screenSizeInTiles y ) tilePositions x, y new System.Drawing.Point(x tileSize, y tileSize) groundBounds x, y, tileSize, tileSize new Microsoft.Xna.Framework.Rectangle(x, y, 20, 20) First off, I'm not sure how to initialize the array groundBounds (I don't know how big to make it). Also, I'm not entirely sure how to go about adding information to groundBounds. I want to add a Rectangle for each tile in the level. Preferably I'd only make a Rectangle for those tiles accessible by the player, and not background tiles, but that's for a different day. FYI, the map was made with a freeware program called Realm Factory.


XNA with WPF or Winforms If you compare integration between WPF with XNA vs Winforms with XNA, what is the most suitable framework to integrate XNA framework with.


How do I get a Model to add a name to it's Texture(s) in the XNA Content Pipeline I know that a texture's name is not preserved when it's loaded in. I also know that you can give it a name. For example Texture2D texture content.Load lt Texture2D gt ("MyTexture") texture.Name "MyTexture" Or whatever else you want to call it However, what about when you load a model? It automatically loads in the right texture for each ModelMeshPart, and drops the Name (no idea why though). This is fine, right up until the point where you actually want to identify which texture that ModelMeshPart is using. I found someone else having the same problem here. Shawn Hargreaves gave this solution If you need access to this data at runtime, you will need to extend the pipeline to store it somewhere else. For instance you could use a custom processor to store texture filenames in the ModelMeshPart.Tag property I figured that was easy enough. Yeah...feel free to point and laugh. I got as far as creating a custom proccessor class and inheriting the standard ModelProcessor before I realised that I didn't know exactly where the ModelMeshPart's texture was stored and I've spent the past few days trying to find out. I just want to preserve each part's texture name so that I can do something like Model model content.Load lt Model gt ("MyModel") BasicEffect effect (BasicEffect)model.Meshes 0 .MeshParts 0 .Effect string texName effect.Texture.Name Also Merry Christmas. EDIT For the record, I'm importing a .x model.


Problem with monogame reference in monodevelop MAC I've downloaded monogame, monotouch (test version) and monodevelop for MAC and I created a monotouch IOS project, I included the Lidgren and Monogame csproject inside my monodevelop project and I added the monogame reference in my project. But when I try to build it, my Main class doesn't find the Game class and Game.run() My Main is the same code that I got monogame site using MonoTouch.Foundation using MonoTouch.UIKit using Microsoft.Xna using Microsoft.Xna.Samples using Microsoft.Xna.Samples.Draw2D namespace Microsoft.Xna.Samples.Draw2D Register ("AppDelegate") class Program UIApplicationDelegate private Game1 game doesn't find public override void FinishedLaunching (UIApplication app) Fun begins.. game new Game1() game.Run() static void Main (string args) UIApplication.Main (args,null,"AppDelegate") and My appDelegate using System using System.Collections.Generic using System.Linq using MonoTouch.Foundation using MonoTouch.UIKit namespace testeios The UIApplicationDelegate for the application. This class is responsible for launching the User Interface of the application, as well as listening (and optionally responding) to application events from iOS. Register ("AppDelegate") public partial class AppDelegate UIApplicationDelegate class level declarations UIWindow window This method is invoked when the application has loaded and is ready to run. In this method you should instantiate the window, load the UI into it and then make the window visible. You have 17 seconds to return from this method, or iOS will terminate your application. public override bool FinishedLaunching (UIApplication app, NSDictionary options) create a new window instance based on the screen size window new UIWindow (UIScreen.MainScreen.Bounds) If you have defined a view, add it here window.AddSubview (navigationController.View) make the window visible window.MakeKeyAndVisible () return true I don't know what's happening, I follow every step to install it. has Someone the same problem?


Basic post processing shader problem I'm trying to create a basic post processing shader, like I did many times before but somehow today it's just not working, I guess it's something basic that I missed. Anyway my setup I have 3 render targets rts 0 , rts1, and rts 2 , I draw a simple model in each one of them. I then draw the render targets to the screen using the following code GraphicsDevice.SetRenderTarget(null) GraphicsDevice.Clear(Color.CornflowerBlue) spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null) spriteBatch.Draw(rts 0 , new Rectangle(0, 0, GraphicsDevice.Viewport.Width 2, GraphicsDevice.Viewport.Height 2), Color.White) spriteBatch.Draw(rts 1 , new Rectangle(GraphicsDevice.Viewport.Width 2, 0, GraphicsDevice.Viewport.Width 2, GraphicsDevice.Viewport.Height 2), Color.White) spriteBatch.Draw(rts 2 , new Rectangle(0, GraphicsDevice.Viewport.Height 2, GraphicsDevice.Viewport.Width 2, GraphicsDevice.Viewport.Height 2), Color.White) spriteBatch.End() This gives me the following picture Which is exactly what I expect it to be ) Now I feed these 3 render targets as textures to my shader like this (shaderTexture is a black 1x1 texture) cutAwayEffect.Parameters "lowTexture" .SetValue(rts 0 ) cutAwayEffect.Parameters "highTexture" .SetValue(rts 1 ) cutAwayEffect.Parameters "cutTexture" .SetValue(rts 2 ) spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque, null, null, null, cutAwayEffect) spriteBatch.Draw(shaderTexture, new Rectangle(GraphicsDevice.Viewport.Width 2, GraphicsDevice.Viewport.Height 2, GraphicsDevice.Viewport.Width 2, GraphicsDevice.Viewport.Height 2), Color.White) spriteBatch.End() And the shader texture lowTexture sampler lowSampler sampler state Texture (lowTexture) texture highTexture sampler highSampler sampler state Texture (highTexture) texture cutTexture sampler cutSampler sampler state Texture (cutTexture) float4 PixelShaderFunction(float2 texCoord TEXCOORD0) COLOR0 float4 baseColour tex2D(lowSampler, texCoord).rgba float4 highColour tex2D(highSampler, texCoord).rgba float4 cutColour tex2D(cutSampler, texCoord).rgba float4 finalColour baseColour highColour cutColour return finalColour technique CutAway pass Pass1 PixelShader compile ps 2 0 PixelShaderFunction() Now I would expect to see a combination of all 3 render targets in the bottom right corner, however I don't see any data from baseColour. When I change finalColour to just baseColour I only see black, same goes for just highColour and just cutColour. Even finalColour highColourcutColour only gives me black while finalColour baseColour highColourcutColour does give me something. The shader does seem to be working, changing final Colour to float4(1,0,1,1) gives me the expected pink square. There seems to be a problem reading the data from the textures, but I've got no clue why.


Issue with importing model to xna I am creating a model with Blender which looks like this and I am importing it into an XNA project. There seems to be some kind of transparency issue. The model looks like that When the camera looks on one side, the side is not shown. Why do I have this problem and what can I do to fix it? PS I am using a custom Effect but I don't think that the issue has something to do with that.


Farseer ApplyForce problem I just tried Farseer and everything is working great. My problem is, that on touch the player should get an force up. Although the touch event works well, the player did not get an force! Here my code public void Update() if (acceleration.Y lt 0) body.Rotation ConvertUnits.ToSimUnits(0.05f) if (acceleration.Y gt 0) body.Rotation ConvertUnits.ToSimUnits(0.05f) while (TouchPanel.IsGestureAvailable) var gesture TouchPanel.ReadGesture() if (gesture.GestureType GestureType.Tap gesture.GestureType GestureType.Flick) Debug.WriteLine("Okey") body.ApplyForce(new Vector2(0, 20)) public void Draw(SpriteBatch spriteBatch) spriteBatch.Draw(playertexture, ConvertUnits.ToDisplayUnits(body.Position),null,Color.White, ConvertUnits.ToDisplayUnits(body.Rotation), new Vector2(playertexture.Width 2, playertexture.Height 2), 1f,SpriteEffects.None, 0f)


How can I read the color of a specific pixel in XNA? I want a way to find out if, for example, the pixel at Vector2(2, 5) on the game window is color Color.Red, or some other color or set of coordinates. How can I do this?


Why does the order matter in multiplication of matrixes? I stumbled on this question because I had the same problem with my camera, and changing the multiplication order worked. I ran into a similar problem when scaling a model. This code produced the wrong result world is an existing Matrix var scale world Matrix.CreateScale(3.2f) whereas this worked perfectly (scaled a model to 3.2x it's size) var scale Matrix.CreateScale(3.2f) world I don't understand why the order matters though in "normal" math (that is, 5 3 vs 3 5), swapping the factors yields the same result. I understand differences if there are more than 2 factors (like in this question), but I don't see the issue here? I don't know much about how Matrices really work and so I don't know if that's an XNA quirk or if it would happen in OpenGL as well?


High definition Full motion background system in XNA I'm mostly just working on this as a hobbyist thing, but here's my problem I got a bit excited over finding the 'Video' and 'VideoPlayer' classes in XNA 4, and hoped to make a game that works a little bit like how Myst does with very active backgrounds, but no actual 3D graphics. (Technically, Myst 1 had static backgrounds, but maybe you get the idea) I threw together a small test game in XNA, with a pretty simple WMV included. The problem I have is that it's not quite responsive enough. I'd like my system to be able to swap the current video in a millisecond, so that the player could click a contraption in the background and instantly see it move. Right now, when I press my trigger key that calls this code private void cycleVideos() videoIndex if (videoIndex videos.Count) videoIndex 0 activeVideo videos videoIndex vp.Stop() Couldn't find a 'Seek(0)' method vp.Play(activeVideo) ...it takes about a full second to re seek the position it needs, and start playing again. In this example, I hadn't even encoded my video to the HD (1920x1080) resolution I had been planning on. I can understand if XNA's video system is really only meant for full cutscenes between missions or that sort of thing I'm willing to use additional memory to have large parts of my videos cached, or even include a bit of a dynamic caching system so that things are loaded unloaded over time (after all, this is the main visual of the game), but I'd like to hear if I have any decent options to accomplish this. I'm also somewhat open to the idea of using a different engine or coding environment entirely. EDIT I've been doing some experimentation in my eagerness to solve this. I can definitely get some faster responsiveness by avoiding the 'stop()' calls, and by maintaining multiple instances of VideoPlayer. A paused video will resume much more quickly and it's possible to play(), then pause() a video immediately (at the beginning of the program, in order to 'cache' it). It's not a full solution yet I want to be able to seek back to the beginning of a video, and I still feel like there should be some possibility of that somewhere.


XNA Error while rendering a texture to a 2D render target via SpriteBatch I've got this simple code that uses SpriteBatch to draw a texture onto a RenderTarget2D private void drawScene(GameTime g) GraphicsDevice.Clear(skyColor) GraphicsDevice.SetRenderTarget(targetScene) drawSunAndMoon() effect.Fog true GraphicsDevice.SetVertexBuffer(line) effect.MainEffect.CurrentTechnique.Passes 0 .Apply() GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2) GraphicsDevice.SetRenderTarget(null) SceneTexture targetScene private void drawPostProcessing(GameTime g) effect.SceneTexture SceneTexture GraphicsDevice.SetRenderTarget(targetBloom) spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque, null, null, null) if (Bloom) effect.BlurEffect.CurrentTechnique.Passes 0 .Apply() spriteBatch.Draw( targetScene, new Rectangle(0, 0, Window.ClientBounds.Width, Window.ClientBounds.Height), Color.White) spriteBatch.End() BloomTexture targetBloom GraphicsDevice.SetRenderTarget(null) Both methods are called from my Draw(GameTime gameTime) function. First drawScene is called, then drawPostProcessing is called. The thing is, when I run this code I get an error on the spriteBatch.Draw call The render target must not be set on the device when it is used as a texture. I already found the solution, which is to draw the actual render target (targetScene) to the texture so it doesn't create a reference to the loaded render target. However, to my knowledge, the only way of doing this is to write GraphicsDevice.SetRenderTarget(outputTarget) SpriteBatch.Draw(inputTarget, ...) GraphicsDevice.SetRenderTarget(null) Which encounters the same exact problem I'm having right now. So, the question I'm asking is how would I render inputTarget to outputTarget without reference issues?


How does this example make efficeint voxel engines using "chunks"? I'm currently looking in to how voxel engines works, with a view to possibly making one, myself. I see a lot of material, like "Let's Make a Voxel Engine", which talks about how to go about reducing the draw calls. What I can't seem to understand is how it actually saves draw call counts, on the basis of the logic being something like the following Without chunks foreach voxel in myvoxels DrawIfVisible() With chunks foreach chunk in mychunks DrawIfVisible() which then does ... foreach voxel in myvoxels DrawIfVisible() Surely, you save nothing by doing this you still make a draw call for each visible voxel, and a visible voxel needs a draw call in either scenario. The only real saving I can see is that the logic that evaluates a chunk will be able to determine if a large number of voxels are visible or not, effectively, saving a bit of "is this chunk visible" CPU time. It's the draw calls that interest me the fewer of those, the faster the application. In case it makes any difference, I will probably be using XNA with DirectX for my engine, so don't consider my choice of example in the link above as my choice of technology. However, this question is such that I doubt it would matter.


XNA C Texture Atlases Fairly new to XNA and not an expert on C either. So I was following a tutorial, specifically this one http rbwhitaker.wikidot.com texture atlases 1, and there is a bit of code I am unfamiliar with. public void Draw(SpriteBatch spriteBatch, Vector2 location) int width Texture.Width Columns int height Texture.Height Rows int row (int)((float)currentFrame (float)Columns) int column currentFrame Columns Mostly all of this I am familiar with. However, the line that says int row (int)((float) currentFrame (float) Columns) This line is not familiar to me and I would appreciate if someone could explain what this does. Clearly it is designed to find out what row the program is on in the texture atlas but what how does it do that with that code? What is it calculating?


What is the most efficient way to blur in a shader? I'm currently working on screen space reflections. I have perfectly reflective mirror like surfaces working, and I now need to use a blur to make the reflection on surfaces with a low specular gloss value look more diffuse. I'm having difficulty deciding how to apply the blur, though. My first idea was to just sample a lower mip level of the screen rendertarget. However, the rendertarget uses SurfaceFormat.HalfVector4 (for HDR effects), which means XNA won't allow linear filtering. Point filtering looks horrible and really doesn't give the visual cue that I want. I've thought about using some kind of Box Gaussian blur, but this would not be ideal. I've already thrashed the texture cache in the raymarching phase before the blur even occurs (a worst case reflection could be 32 samples per pixel), and the blur kernel to make the reflections look sufficiently diffuse would be fairly large. Does anyone have any suggestions? I know it's doable, as Photon Workshop achieved the effect in Unity.


Alpha blend 3D png texture in XNA I'm trying to draw a partly transparent texture a plane, but the problem is that it's incorrectly displaying what is behind that texture. Pseudo code vertices1 basiceffect1 The vertices of vertices1 are located BEHIND vertices2 vertices2 basiceffect2 The vertices of vertices2 are located IN FRONT vertices1 GraphicsDevice.Clear(Blue) PrimitiveBatch.Begin() if I draw like this PrimitiveBatch.Draw(vertices1, trianglestrip, basiceffect1) PrimitiveBatch.Draw(vertices2, trianglestrip, basiceffect2) Everything gets draw correctly, I can see the texture of vertices2 trough the transparent parts of vertices1 but if I draw like this PrimitiveBatch.Draw(vertices2, trianglestrip, basiceffect2) PrimitiveBatch.Draw(vertices1, trianglestrip, basiceffect1) I cannot see the texture of vertices1 in behind the texture of vertices2 Instead, the texture vertices2 gets drawn, and the transparent parts are blue The clear color PrimitiveBatch.Draw(vertice PrimitiveBatch.End() My question is, Why does the order in which I call draw matter? Edit Added screenshots It's like there is no Z buffering at all. this is done with GraphicsDevice.DepthStencilState DepthStencilState.DepthRead I've tried other settings but they don't help Edit I think I have to somehow set the BlendState of the graphic card in some way so that the textures behind other textures get rendered.


Why are my polygons not opaque? A newbie to XNA here. This is a followup to my previous question that showed me part of what I was doing wrong but I'm still not getting what I want. I'm setting up a BasicEffect thus Effect new BasicEffect(GraphicsDevice) Effect.VertexColorEnabled true Effect.Alpha 1.0f Effect.GraphicsDevice.DepthStencilState DepthStencilState.Default Effect.GraphicsDevice.BlendState BlendState.Opaque and the draw loop GraphicsDevice.Clear(ClearOptions.Target ClearOptions.DepthBuffer, Color.Black, MaxDepth, 0) All polygons are being rendered where and how I wish except they should be fully opaque and they aren't. The actual image looks more like the various colors are being combined in a fashion I'm not sure about


Issue With Image Rendereing I'm pretty New to the XNA Side of things, I have built in PhotoShop a Set of frame by Frame images side by side to go through an animation class to display them frame by frame. With this my images will not show up properly, they look more like a film reel. Were could I Ggt good information on images for animation for XNA?


Scale my pixel art files when designing them or when rendering? If I create pixel art files that need to be scaled up on the screen later, so that a single pixel becomes a box of 4 pixels. Should I create my pixel art with 2x2 pixels or should I create it with 1x1 pixels so that I can I 1 2 scale it later in XNA to 2x2 pixels? I tend to believe that 1 1 would result in too much detail rather than the pixel art effect, thus I want the end result in 2 1 style where a 1x1 pixel of my intended sprite will take 2x2 pixels on the screen.


How to retrieve a cube collision by faces I work for a while on a minecraft game (voxel). I am front a problem for a long time about the collision detection. I want recover the cubes collision from my highlighted black's cube like on the picture , but only on the sides. And not on the edges ! Actually i got all cubes in red and green when i check with the boundingBox method. Actually i use the method with the class "BoundingBox" to check for collisions. Can anyone help me or direct me on the best way for retrive the right cube ? Code example with the boundingBox methode for check the collision List lt Node gt nodeParent regions modelSelected.regionIndex .Nodes modelSelected.Id .Where(m gt modelSelected.BoundingBox.Intersects(m.boundingBox)).ToList() i want to get only the green cube and not the red .. From the black cube in the middle Thank's a lot guy


How do I get the height of an XNA SpriteFont? I have some text in a spritefont and I need to know the height in pixels. I would have thought that MeasureString() would get me close to it, but it seems to just be about length.


Different number of lights different shader I have a shader that computes lighting for each light. PointLight PointLights 10 uniform const float NumPointLights for(int i 0 i lt NumPointLights i ) lightVec PointLights i .Position pos lightDist length(lightVec) Do other stuff with light here, etc. If I set NumPointLights to 2, the loop still iterates 10 times, and discards the result of the last 8 iterations. Should I set a compiler flag that will permit the loop to actually loop only 8 times, or should I make 10 shaders, a shader for each number of lights that can be rendered? On some small pieces of geometry I occaisionally need 10 lights. 90 of the time I only need 1 2 lights. How do I proceed?


XNA HLSL what happens if I grab a pixel outside a texture? I'm using the tex2D function of HLSL, and I am wondering what will happen if I try to grab a pixel from a pixel coordinate outside of my texture (as an example 1.1). Will it clamp? Will it repeat the texture and grab something else? Will it return transparent?


XNA GameComponent.Initialize() not called I have a game which creates an object in its Initialize() method private GameComponent1 thingy protected override void Initialize() Game1.Initialize() base.Initialize() thing new GameComponent1(this) In the GameComponent1 class public GameComponent1(Game1 game) base(game) game game game.Components.Add(this) public override void Initialize() GameComponent1.Initialize() Do stuff here base.Initialize() However, in this case, thing's Initialize method is not called. Why is this? It behaves fine when the object is created in, say, Game1's Update method...


Rotating a vector by a quaternion I am trying to rotate a direction vector (0,0,1,0) by a rotation quaternion in DirectX. From what understanding, to rotate the vector you must do NewVector rotQuaternion Vector inverse(rotQuaternion) In directX11, I am testing out the algorithm above using an identity quaternion. XMVECTOR qIdentity XMQuaternionIdentity() XMVECTOR inverse XMQuaternionInverse(qIdentity) XMVECTOR test qIdentity XMVectorSet(0.0f,0.0f,1.0f,0.0f) inverse My new test vector should just be (0,0,1,0), however it is completely zeroed out, and I am not exactly sure why or if I multiplied it correctly.


In XNA, how do I dynamically load parts of a large 2D world map? I want to develop a huge world map at least 8000 6000 pixels in size. I have broken it into a 10 10 grid of 800 600 pixel PNG images. To avoid loading everything into memory, the images should be loaded and unloaded depending on the player's position in the grid. For example, here is the player at position (3,3) As he moves to the right to (4,3), the three images at the far left are deallocated while the three images at the right are allocated There should probably be a threshold inside each cell of the grid triggering the loading and unloading. The loading should probably happen in a separate thread. How do I design such a system?


What do I need to do to my slope collision detection to prevent the player from passing through my collision? I've recently implemented slope collision detection for my project. The issue I'm having is that the character occasionally passes through the line. This usually occurs when the characters MoveAcceleration is increased from 5000 to 8000 via a game mechanic. I was wondering if there is a way to make the line collision more reliable without reducing the MoveAcceleration variable ? This is how the characters position is calculated velocity.X movement MoveAcceleration elapsed Position velocity elapsed This is how the slopeCollision is handled private void HandleSlopeCollisions(GameTime gameTime) isOnSlope false float elapsed (float)gameTime.ElapsedGameTime.TotalSeconds if (velocity.Y gt 0) if (attachedPath ! null) isOnSlope true position.Y attachedPath.InterpolateY(position.X) velocity.Y 0 if (position.X lt attachedPath.MinimumX position.X gt attachedPath.MaximumX) attachedPath null else Vector2 footPosition position Vector2 expectedFootPosition footPosition velocity elapsed CollisionPath landablePath null float landablePosition float.MaxValue foreach (CollisionPath path in collisionPaths) if (expectedFootPosition.X gt path.MinimumX amp amp expectedFootPosition.X lt path.MaximumX) float pathOldY path.InterpolateY(footPosition.X) float pathNewY path.InterpolateY(expectedFootPosition.X) if (footPosition.Y lt pathOldY amp amp expectedFootPosition.Y gt pathNewY amp amp pathNewY lt landablePosition) isOnSlope true landablePath path landablePosition pathNewY if (landablePath ! null) isOnSlope true velocity.Y 0 footPosition.Y landablePosition attachedPath landablePath position.Y footPosition.Y else attachedPath null


Texture in model not rendered by BasicEffect UPDATE It is apparently the BasicEffect that is the culprit here. I tried to use another effect (which I coded myself) and then it works!?!? )I kinda like the EnableDefaultLighting, though...) So this question is now rephrased to "what in the model exported by Blender can cause BasicEffect to fail to render the texture?". I have imported this model into Blender and exported it to an .fbx file and imported it into my XNA project. The problem is that the model is pitch black (just as it is in Blender when I look at it in object mode) when drawn in XNA. I have verified that the texture really is there (and that only one iteration is made) foreach (var mesh in model.Meshes) foreach (var part in mesh.MeshParts) if (part.Effect is BasicEffect) var be part.Effect as BasicEffect using ( var stream File.Create( "c test.jpg") ) be.Texture.SaveAsJpeg(stream,2048,2048) I have followed exactly the same procedure with other models and it has worked. Since the model looks good in Blender and the textures really makes it into XNA... what can be wrong here? For what it's worth one difference from what I'm used to is that these textures are not stored inside the .fbx but in a separate subfolder, but the XNA content importer finds them (I get an error if I try to remove them). UPDATE it may be important to mention that this model actually has three textures diffuse, specular and normal maps. However, ONE of them should be projected by the BasicEffect, right? UPDATE a screen shot from Blender.


Reading messages from a certain client in Lidgren I'm setting up a game with Lidgren, and I was wondering if there was a way to read a message from a certain client instead of just from the server as a whole, such as Why doesn't this exist? NetIncomingMessage message server.Connections 0 .ReadMessage() This way I would be able to split up reading data from each client into it's own thread and have a separate thread for sending data to each client. Currently there is only one loop in my server, which reads packets and I fear is favoring one client more than others, as some movements made by players take a while to be received by other players. I believe reading messages separately from each client would solve this issue. With simple TcpClients, you can read from each client's stream instead of the server as a whole, and I like this functionality but also rely on the simplicity of sending packets through Lidgren and was wondering if there was a similar functionality with Lidgren.


Confused about order of operation when using a Matrix in XNA, C Here are two different pieces of code This is what I started with Vector2 hold Vector2.Transform(pos1, mat1) Matrix inv Matrix.Invert(mat2) Vector2 pos2 Vector2.Transform(hold, inv) And this is what i'm told is the simplified version Matrix matrix1to2 mat1 Matrix.Invert(mat2) Vector2 pos2 Vector2.Transform(pos1, matrix1to2) What I don't understand is, why isn't the first line in the simpilifed version Matrix matrix1to2 Matrix.Invert(mat2) mat1 Since in matrix order it looks like the matrix on the right would take effect first and in the original we have mat1 being multiplied in first Another example, The following image shows the order of operations desired http www.riemers.net images Tutorials XNA Csharp Series2D mat1.png The tutorial says that to create this transformation you use Matrix carriageMat Matrix.CreateTranslation(0, carriage.Height, 0) Matrix.CreateScale(playerScaling) Matrix.CreateTranslation(xPos, yPos, 0) Matrix.Identity How could this work if the the order was left to right?


When do you get Mouse.getstate().X or Y as negative? I am creating a game in which I use a function int x() int px 100 int pxend 128 int xx 0 for (int i 0 i lt 6 i ) l Mouse.GetState().X if (l gt px amp amp l lt pxend) xx px break else px 128 pxend 128 return xx and int y() int px 100 int pxend 128 int xx 0 for (int i 0 i lt 4 i ) l Mouse.GetState().X if (l gt px amp amp l lt pxend) xx px break else px 128 pxend 128 return xx But when I debug I get value a l as negative even though the debug is initiate after a click on the GameWindow screen. Sometimes it works fine sometime does not. I dont know why does it give me negative value. And when I used them with my Rectangle i get Rectangle.X and Rectangle.Y as 0.


enemy View Range , chase player for 3D Q1 I want to make zone range for each enemy in the game , so that when the player in the view range he will be chased . Q2 if I want to make enemy walk a little bit around his position ( from 10 to 10 ) for example , i.e as he is searching for some one , can you give me just steps ! thanks Q3 How to make enemy moves toward Player if he is being detected ? Sorry for question , but I am new to this world )


XNA 4.0 Point Vertex Rendering I have a buffer of about 134 million particles and a very powerful computer to render them smoothly, but I am getting an error when trying to render them as primitive lines. It says that I cannot render more than around 1 million. Is there a way I can do this? Is there a better way to render this other than with lines? I'm comfortable with having 1 pixel points or anything as long as the vertices are shown all the time. I'm basically just plotting the points.


XNA Where should I start playing a song? I am just wondering where is the best place to start playing the background song for a game. In the loadContent() method, Draw(), or Update() methods or when I initialize it? I am trying to make it so that the song starts playing at the same time the screen appears.


XNA, SpriteBatch Slow when rendering lots of sprites? I've just now tested rendering a lot of sprites using XNA's SpriteBatch class. What I basically do is this Somewhere in the code, I have a list which contains all sprites that have to be rendered. I prefilled this list with 2500 Sprites, all of which have the same rotational angle, texture, position etc. I then draw them like this spriteBatch.Begin() foreach (Sprite spr in sprites) spriteBatch.Draw(spr.Texture, spr.Position spr.Center, spr.SourceRect, spr.Color,MathHelper.ToRadians( spr.Rotation ), spr.Center, spr.Scale, SpriteEffects.None, spr.Depth) spriteBatch.End() and I'm getting really poor performance. I only average about 15FPS with my Radeon HD 6850 graphics card and i5 2500k CPU. This is very surprising to me, since I average about 70 FPS doing exactly the same thing with my own custom OpenGL engine, which uses old OpenGL rendering (meaning one draw call for every single sprite). I actually expected XNAs rendering to be a ton faster, since it draws everything in one draw call. Am I rendering this the wrong way? Playing around with SpriteSortMode settings has made almost no difference, some of them just make it a tiny bit slower (depth sorting etc.).


Artificial Intelligence when to update pathfind? Right now I have a pathfind algorithm A so I'm already using it to move the player around. My problem comes to the NPC'S. They find the path to the player but if the player change the position they have to find a new path all the time? or there's something I can do to avoid so many calculations? Example I have an enemy 5 units of distance from the player. He moves to 4 units of distance based in the path he already found and then search the path again? or does he make half of the path until he search for a new path? I imagine making that for 5 or more enemies may make the game slow? (I never tested it before) Any toughs?


In XNA 3.1, is it possible to disable texture filtering? I want to disable texture filtering (since I'm making a retro style game where it looks bad if a texture gets filtered like that), but since I'm on XNA 3.1 there seems to be no option to set a SamplerState with SpriteBatch.Begin or anything. Is it possible to do this?


Why are my sprite outlines partially rendering in the wrong place? I've been trying to draw an outline around a sprite using the code from this answer. Details My sprite is called Ship2Sprite. This is how I create the rectangle rectangle New Rectangle(backgroundPos.X NPCAI.enemyPosistion.X, backgroundPos.Y NPCAI.enemyPosistion.Y, Ship2Sprite.Width, Ship2Sprite.Height) This is how it looks without any rectangle drawn If I use this line of code hudSpriteBatch.Draw(t, rectangle, New Rectangle(0, 0, 0, 0), Color.Red, NPCAI.enemyAngle, New Vector2(0, 0), SpriteEffects.None, 0) the following is the result in game hudSpriteBatch.Draw(t, New Rectangle(rectangle.Left, rectangle.Top, 2, rectangle.Height), New Rectangle(0, 0, 0, 0), Color.White, NPCAI.enemyAngle, New Vector2(0, 0), SpriteEffects.None, 0) hudSpriteBatch.Draw(t, New Rectangle(rectangle.Right, rectangle.Top, 2, rectangle.Width), New Rectangle(0, 0, 0, 0), Color.White, NPCAI.enemyAngle, New Vector2(0, 0), SpriteEffects.None, 0) hudSpriteBatch.Draw(t, New Rectangle(rectangle.Left, rectangle.Top, rectangle.Width, 2), New Rectangle(0, 0, 0, 0), Color.White, NPCAI.enemyAngle, New Vector2(0, 0), SpriteEffects.None, 0) hudSpriteBatch.Draw(t, New Rectangle(rectangle.Left, rectangle.Bottom, rectangle.Width, 2), New Rectangle(0, 0, 0, 0), Color.White, NPCAI.enemyAngle, New Vector2(0, 0), SpriteEffects.None, 0) However, when trying to use the code from the linked answer, this is the result The first and third lines produce the correct lines, however the other 2 are in the correct orientation but not the correct position Am I missing something somewhere? EDIT Based on Blau's answer, I have updated my code to this Public Shared Sub DrawOutline(ByVal t As Texture2D, ByVal sprite As Texture2D, ByVal pos As Vector2, ByVal graphics As GraphicsDevice) Dim spriteBatch1 As New SpriteBatch(graphics) Dim rectangle As New Rectangle(Game.backgroundPos.X pos.X, Game.backgroundPos.Y pos.Y, sprite.Width, sprite.Height) Dim w rectangle.Width Dim h rectangle.Height Dim x rectangle.X w 2 Dim y rectangle.Y h 2 Dim transform As Matrix Matrix.CreateRotationZ(NPCAI.enemyAngle) Matrix.CreateTranslation(x, y, 0) spriteBatch1.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, Nothing, Nothing, Nothing, Nothing, transform) x w 2 y h 2 spriteBatch1.Draw(t, New Rectangle(x, y, w, 2), Nothing, Color.White) spriteBatch1.Draw(t, New Rectangle(x, y h 2, w, 2), Nothing, Color.White) spriteBatch1.Draw(t, New Rectangle(x, y, 2, h), Nothing, Color.White) spriteBatch1.Draw(t, New Rectangle(x w 2, y, 2, h), Nothing, Color.White) spriteBatch1.End() End Sub However the rectangle is rendering in the wrong position, which is slightly ahead of the sprite. Like this EDIT 2, with the following code Public Shared Sub DrawOutline(ByVal t As Texture2D, ByVal sprite As Texture2D, ByVal pos As Vector2, ByVal graphics As GraphicsDevice, ByVal angle As Single) Dim spriteBatch1 New SpriteBatch(graphics) Dim rectangle As New Rectangle(Game.backgroundPos.X pos.X, Game.backgroundPos.Y pos.Y, sprite.Width, sprite.Height) Dim w rectangle.Width Dim h rectangle.Height Dim x rectangle.X w 128 Dim y rectangle.Y h 128 Dim transform As Matrix Matrix.CreateRotationZ(angle) Matrix.CreateTranslation(x, y, 0) spriteBatch1.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, Nothing, Nothing, Nothing, Nothing, transform) x w 128 y h 128 ' spriteBatch1.Draw(t, rectangle, Color.Red) spriteBatch1.Draw(t, New Rectangle(x, y, w, 2), Nothing, Color.White) spriteBatch1.Draw(t, New Rectangle(x, y h 2, w, 2), Nothing, Color.White) spriteBatch1.Draw(t, New Rectangle(x, y, 2, h), Nothing, Color.White) spriteBatch1.Draw(t, New Rectangle(x w 2, y, 2, h), Nothing, Color.White) spriteBatch1.End() End Sub


How does Texture2D.GetData return coloured pixels? I'm trying to work out how the pixels are stored in the returned array but I'm not having a lot of luck (and thus my calculations don't seem to be working). I realize that the pixels are stored in one long continuous array but are the pixels grabbed width first or height first? I've tried drawing out the "pixels" of a texture on paper to calculate where the pixels should be based on the single array but I'm not getting expected results. My assumption is the following Assuming I am using i to specify rows and j to specify columns that any given pixel in a 2D texture can be calculated by the sum of i j or is this incorrect?


2D Scrolling Background on XNA How do I create a scrolling X and scrolling Y background without weird things happening like the player disappearing or not getting the offset correct? I have code at https vanillity.kilnhg.com Code Repositories Group Aremac Looks like this var s game.gd.Viewport.Bounds var g game.world.Bounds var p game.player.Bounds var v viewRectangle var x p.X 0 ? p.X s.Width 2 v.Right 1090 ? 90 p.X s.Width 2 ? p.X s.Width 2 0 var y v.Bottom p.Y s.Height 2 ? p.Y s.Height 2 0 var w s.Width var h s.Height view Rectangle Offset new Vector2(x , y) viewRectangle new Rectangle( x, y ,w, h) and then source rectangle var x (int)0 var y (int)0 var g game.world.Bounds var w g.Width var h g.Height var rect new Rectangle(x,y,w,h) spriteBatch.Draw( w.boundsTexture ,rect ,viewRectangle ,w.Color ,0 ,Vector2.Zero ,SpriteEffects.None ,1 ) Before center, the grey guy is holding the rock in his left hand After center, the rock (and the white guy) drifts evermore to the right


XNA Line to Rectangle Collision return first pixel I have the following code public static bool LineIntersectsRect(Point p1, Point p2, Rectangle r) return LineIntersectsLine(p1, p2, new Point(r.X, r.Y), new Point(r.X r.Width, r.Y)) LineIntersectsLine(p1, p2, new Point(r.X r.Width, r.Y), new Point(r.X r.Width, r.Y r.Height)) LineIntersectsLine(p1, p2, new Point(r.X r.Width, r.Y r.Height), new Point(r.X, r.Y r.Height)) LineIntersectsLine(p1, p2, new Point(r.X, r.Y r.Height), new Point(r.X, r.Y)) (r.Contains(p1) amp amp r.Contains(p2)) private static bool LineIntersectsLine(Point l1p1, Point l1p2, Point l2p1, Point l2p2) float q (l1p1.Y l2p1.Y) (l2p2.X l2p1.X) (l1p1.X l2p1.X) (l2p2.Y l2p1.Y) float d (l1p2.X l1p1.X) (l2p2.Y l2p1.Y) (l1p2.Y l1p1.Y) (l2p2.X l2p1.X) if (d 0) return false float r q d q (l1p1.Y l2p1.Y) (l1p2.X l1p1.X) (l1p1.X l2p1.X) (l1p2.Y l1p1.Y) float s q d if (r lt 0 r gt 1 s lt 0 s gt 1) return false return true This code checks to see if a line intersects a given rectangle. But I need to find a way to get the position of the first pixel colliding between Point 'p1' and Point 'p2'. Any help is appreciated.


Monogame Render Target antialiasing doesn't work Is there any proper way to use antialiasing, while rendering to a RenderTarget2D and using Monogame? I do this renderTarget new RenderTarget2D(GameData.GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, false, GameData.GraphicsDevice.DisplayMode.Format, DepthFormat.Depth24, 4, RenderTargetUsage.DiscardContents) but AA is disabled despite setting multiSampleCount to 4. The hardware supports it and it works if rendering directly to the back buffer. I googled around and it seems it used to work for XNA, but for Monogame I found this https github.com mono MonoGame issues 1162 This link suggests it's an open issue and is from 2013. This is hard to believe for me, because it would effectively make using Monogame render targets unusable for most applications..


How to determine depth of a pixel perfect collision I am trying to figure out how to determine the depth of a pixel perfect collision in XNA. I want to know the depth in order to be able to use it in my collision response. At the moment I have the following code, that provides me with a working pixel perfect collision detection public static bool IntersectPixels(Matrix transformA, int widthA, int heightA, Color dataA, Matrix transformB, int widthB, int heightB, Color dataB) Matrix transformAToB transformA Matrix.Invert(transformB) Vector2 stepX Vector2.TransformNormal(Vector2.UnitX, transformAToB) Vector2 stepY Vector2.TransformNormal(Vector2.UnitY, transformAToB) Calculate the top left corner of A in B's local space This variable will be reused to keep track of the start of each row Vector2 yPosInB Vector2.Transform(Vector2.Zero, transformAToB) For each row of pixels in A for (int yA 0 yA lt heightA yA ) Start at the beginning of the row Vector2 posInB yPosInB For each pixel in this row for (int xA 0 xA lt widthA xA ) Round to the nearest pixel int xB (int)Math.Round(posInB.X) int yB (int)Math.Round(posInB.Y) If the pixel lies within the bounds of B if (0 lt xB amp amp xB lt widthB amp amp 0 lt yB amp amp yB lt heightB) Get the colors of the overlapping pixels Color colorA dataA xA yA widthA Color colorB dataB xB yB widthB If both pixels are not completely transparent, if (colorA.A ! 0 amp amp colorB.A ! 0) then an intersection has been found return true Move to the next pixel in the row posInB stepX Move to the next row yPosInB stepY No intersection found return false How would I determine how deep the collision is into the dataB texture data?


How to prevent a character from going up a steep hill with a height map? I've been trying to make my character unable to go up steep hills, but I just can't manage to make it work. I'm using a simple height map which stores the height for every (x, z) point within the map. I've tried to do this(using C and XNA) float height1 TerrainHeightAt(cam.Position) float height2 TerrainHeightAt(cam.Position cam.GetVelocity()) If the difference between the two is bigger than a certain constant, don't move. Basically I find the current height and the future height of the camera. Then, I check if the character is attempting to go up a too steep hill, and if so, I prevent the character from moving. This is not working and I can't see why it isn't. So my question is What am I doing wrong? I would appreciate any link(specially using XNA, but general articles would be great too) showing how to achieve this. Thank you.


XNA C How can I prevent blurring when drawing from a RenderTarget2D? I'm making a game and I want the end graphics to look chunky and pixellated, so I'm drawing from the spritebatch onto a RenderTarget2D which is 1 4th the size of the actual backbuffer, and then drawing from that to the backbuffer. At first the sprites were blurred by antialiasing and I read that using SamplerState.PointWrap in the spritebatch Begin call would ease this a bit so I made that change. Everything seemed better, however the final on screen image is still blurry and I think this is because of how it draws from the rendertarget2D to the backbuffer. The image here is a comparison On the left is how the output looks now and the right is how I want it to look.


Finding a way to display objects efficiently I am making a 2D simple Breakout game, and I would like to know of an efficient way to display all the blocks on the screen. I was thinking of dividing the whole screen into little squares that can be occupied by a block or a wall (or most objects). Is this the best way of doing it? Sorry if my question is kinda noob ish, I just started learning to develop games.


Additional dependencies in XNA Monogame I made a game in monogame recently, using the XNA content pipleline. I then sent the whole folder (The release folder in visual studio) to a friend of mine who does not have visual studio or monogame. He said he can't open the game. What the are files I need to give my friend for him to be able to play it? He has Windows 8


Load all content from folder I want to ask, is there way to load in xna all content from folder ? For example in my content I have Images hero Images car Images tree I want to make something like this Dictionary lt string,Model gt models new ... foreach(string name in content.getNames("Images")) models name content.load lt Model gt ("Images " name)


Is it normal that "Game.Run" in XNA uses a lot of resources? I have been using the visual studio profiler to optimize my game. I have noticed that the Game.Run method is eating through 93.6 of the overall game resources. Is this because all of the other functions are called by it in the game? Or is there a problem? I am quite new to the VS profiler and have in the past not used such applications to assist in optimizing.


Loading images in XNA 4.0 "Cannot Open File" Problems Okay, I'm writing a game in C XNA 4.0 and am utterly stumped at my current juncture Sprite animation. I understand how it works and have all the code in place, but my ContentLoader won't open my file... Basically, my directory looks like this WindowsGame1 "Game1.cs" Classes "NPC.cs" Content Reference Images "Monster.png" Inside my NPC class, I have all the essential drawing functions, i.e. LoadContent, Draw, Update. And I can get the game to find the correct file and attempt to open it, but when it tries, it throws an exception and tells me it can't open the file. This is how my code in my NPC class looks Texture2D NPCImage Vector2 NPCPosition Animation NPCAnimation new Animation() public void Initialize() NPCAnimation.Initialize(NPCPosition, new Vector2(4, 4)) public void LoadContent(ContentManager Content) NPCImage Content.Load lt Texture2D gt (" InsertImageFilePathHere ") NPCAnimation.AnimationImage NPCImage The rest of the code is irrelevant at this point because I can't even get the image to load. I think it might have to do with a directory problem, but I also know little to nothing about spriting or working with images or animations in my code. Any help is appreciated. Not sure if I provided enough information here, so let me know if more is needed! Also, what would be the correct way to direct that Content.Load to Monster.png given the current directory situation? Right now I just have it using the full path from the C drive. Thanks in advance!


Primitives does not show on screen I'm trying to render terrain, everything compiles fine, but I can't see anything on screen. ( I'm moving camera around in case it was on the other side) Can't figure out whats wrong. public class Terrain public VertexBuffer vertexBuffer public IndexBuffer indexBuffer public VertexPositionNormalTexture vertices public int indices int gridSize Camera camera ContentManager Content GraphicsDevice device Texture2D heightmap public Texture2D grass Effect effect public Terrain(ContentManager Content, GraphicsDevice device, Camera camera) this.Content Content this.device device this.camera camera heightmap Content.Load lt Texture2D gt ("Gfx heightmap") grass Content.Load lt Texture2D gt ("Gfx grass") effect Content.Load lt Effect gt ("Effects terrain") CreateVertices() CreateIndices() public void Draw() effect.CurrentTechnique effect.Techniques "Texture1" effect.Parameters "xWorldViewProjection" .SetValue(camera.worldMatrix camera.viewMatrix camera.projMatrix) effect.Parameters "xTexture" .SetValue(grass) foreach (EffectPass pass in effect.CurrentTechnique.Passes) pass.Apply() device.DrawUserIndexedPrimitives lt VertexPositionNormalTexture gt (PrimitiveType.TriangleList, vertices, 0, vertices.Length, indices, 0, indices.Length 3) private void CreateVertices() vertices new VertexPositionNormalTexture heightmap.Width heightmap.Height for (int x 0 x lt heightmap.Width x ) for (int y 0 y lt heightmap.Height y ) vertices y heightmap.Width x .Position new Vector3(x, 0, y) vertices y heightmap.Width x .Normal new Vector3(0, 1, 0) vertices y heightmap.Width x .TextureCoordinate new Vector2(y, x) device.SetVertexBuffer(vertexBuffer) private void CreateIndices() indices new int (heightmap.Width 1) (heightmap.Height 1) 6 int counter 0 for (int x 0 x lt heightmap.Width 1 x ) for (int y 0 y lt heightmap.Height 1 y ) int lowerLeft x y heightmap.Width int lowerRight (x 1) y heightmap.Width int topLeft x (y 1) heightmap.Width int topRight (x 1) (y 1) heightmap.Width indices counter topLeft indices counter lowerRight indices counter lowerLeft indices counter topLeft indices counter topRight indices counter lowerRight


Using shader for cubes I am trying to use a shader to get an effect like this. Notice how every cube has exactly the same lightning as every other no matter where it is on the screen if you look closely the lightning is making the front face's top parts darker, and the front face's lower parts lighter (about 20 difference at most) also more importantly the edges of the cubes are smoothed ( filleted ) and foggy looking I am drawing my cubes like this with the default lightning. cubeEffect.EnableDefaultLighting() for (int i 0 i lt 10 i ) for (int j 0 j lt 25 j ) apply the effect and render the cube foreach (EffectPass pass in cubeEffect.CurrentTechnique.Passes) cubeEffect.World Matrix.CreateTranslation( 15.6f i 3.05f, 15.5f j 1.168f, 0.0f) pass.Apply() draw RenderToDevice(GraphicsDevice) This is how my cubes looks like with the default lightning... i am trying to achieve an effect like the first image. I have no experience with lightning effects and how to do something like this so, i'd appreciate any help on how to get started. I used this http blogs.msdn.com b dawate archive 2011 01 20 constructing drawing and texturing a cube with vertices in xna on windows phone 7.aspx tutorial's help to draw this


XNA How to Flip Mirror a position over a custom vector? I want to flip Horizontally my Sprite Texture however the SpriteEffects.FlipHorizontally isn't cutting it for me as it just flips the texture in place. I want to flip the texture over a specified Vector2 Vector3? Thanks!


XNA Making 2D Hexagons Connect With Each Other I'm working on a top down 2D strategy game in XNA, and the tiles are hexagons. I can't have a grid because of the game mechanics, so everything has its own location, and every tile object is stored in a list. What I'm trying to do is have it so that if you place a tile close to the side of another tile, they will snap together and become one object. I can't seem to figure out how to get what side it should snap to. The red represents the different sections I want to check for mouse clicks in (these would of course not be an actual texture in the game). The white represents the area where if you clicked, it wouldn't allow you to place a tile because it would be on top of another. The closest thing I can think of is to have a larger hexagon around the actual tile that's divided into triangles from the center to the edges, but I'm not sure how to do this. And I'm gonna move it to Windows Phone with Monogame and I don't think the phone is fast enough to make some sort of thing that checks colors for each sector, so I don't think it can be texture based. I feel like there's some kind of relatively simple math to do this but I can't seem to figure it out.


transform touch click coordinates(2D) into 3d coordinates I would like to convert touch click input (2D coordinates) to 3D coordinates by dropping the Z axis (would like to move only up down, left right (Z is the axis for depth). The problem is that the coordinates i get from input (2d) aren't corelated with the 3d actual space. Does XNA provide a way to do this?


Best pathfinding algorithm for a tower defense game? What do you suggest would be the best algorithm for a tower defense game? It's a 2D based tile game, where there is walls and towers blocking the way, between spawnpoints and their destination points. Constantly, as the player places a new tower to block the way, or to help shoot spawning units before they reach their destination, a new path for the affected spawnpoint's path will have to be recalculated, and the units must be re routed to that new path. Therefore, I need performance. I tried the A algorithm, but everytime the player places a new tower, and path has to be recalculated, the existing units who haven't gone past the tower yet, get lost, and stand still, since they were a part of the old path that has now lost its pathing information.


Does XNA 4 support 3D affine transformations for 2D images? Looooong story short I'm essentially trying to code Mode 7 in XNA. Before I continue bashing my brains out in research and various failed matrix math equations I just want to make sure that XNA supports this just out of the box (so to speak). I'd prefer not to have to import other libraries, because I want to learn how it works myself that way I understand the whole thing better. However that's all for naught if it won't work at all. So no opengl, directx, etc if possible (will eventually do it just to optimize everything, but not for now). tl dr Can I has Mode 7 in XNA?


XNA Distortion Shader problem So I came up with a distortion pixel shader in hlsl, but it has some issues. First of all, here is how it works The shader uses another texture generated by the program as a distortion "map" (if that's the correct term) I called this map a "mask". The shader uses the red values in the mask for horizontal distortion and the blue values as vertical distortion. The green values are not used. It subtracts 0.5 from the red and green values so that they have a range from 0.5 to 0.5 instead of 0 to 1. This lets the distortion go in any direction using only two color values. I let the shader "push" pixels up to 128 pixels. sampler s0 texture textu sampler tex sampler sampler state Texture textu float2 screenSize float4 PixelShaderFunction(float2 coords TEXCOORD0) COLOR0 float4 tex color tex2D(tex sampler, coords) if (tex color.a) float distX (tex color.r 0.5f) (256.0f screenSize.x) tex color.a float distY (tex color.b 0.5f) (256.0f screenSize.y) tex color.a return tex2D(s0, float2(coords.x distX, coords.y distY)) return tex2D(s0, coords) technique Technique1 pass Pass1 PixelShader compile ps 2 0 PixelShaderFunction() "textu" being the mask, "tex color" is the color value from the mask. It also multiplies the distortion by the alpha value in the mask. This seemed to work perfectly at first, but I started noticing some issues. I was using a completely white texture (as the mask) that was blurred around the edges. I set the color of this texture based on its rotation. Here is the method I used for that private Color GetDirectionColor(float rad) Vector2 v new Vector2( (float)Math.Cos(rad Math.PI), (float)Math.Sin(rad Math.PI) ) float r (v.X 0.5f) 0.5f float b (v.Y 0.5f) 0.5f return new Color(new Vector3(r, 0, b)) This allows the texture to "push" pixels in whatever direction it is facing. This method seems to work fine. The problem is, when the texture is rotated more than 135 degrees and less than 315 degrees (as in, the texture is pointing into the upper left half of a circle if you cut it in half at a 45 degree angle) it does something strange. Where the texture is blurred (the alpha values become less than 1) it starts to "push" the pixels in the opposite direction that it should be. I suspect this has to do with my shader and not something else in the program. Possibly the 0.5f part??? I'm terribly sorry if this is confusing... I could not find a better way to word it. Thanks a lot for your help!


XNA MonoGame and Game Studio MonoDevelop First off, I have a bit of programming experience in Java and have always programmed using ViM (even though I recently moved to Sublime Text 2) and I'm trying to learn C and the MonoGame framework. My question is whether or not I REALLY need MonoDevelop. So, do I really need Visual Studio MonoDevelop to develop games in C and MonoGame?


How does XNA's KeyboardState represent all keyboards? I already understand how to work with Keyboard and KeyboardState, but when debugging I happened to take a look at the KeyboardState's non public members via the VS debugger. I expected to see a large list of values, but instead, only saw 8 uints at a static level, and another 8 uints per instance Non Public members (static) stateMask0 uint 976757505 stateMask1 uint 67108863 stateMask2 uint 3221225470 stateMask3 uint 4294967295 stateMask4 uint 196863 stateMask5 uint 4244635647 stateMask6 uint 4160752641 stateMask7 uint 1876688932 Non Public members (instance) currentState0 uint 0 currentState1 uint 0 currentState2 uint 0 currentState3 uint 1048576 currentState4 uint 0 currentState5 uint 0 currentState6 uint 0 currentState7 uint 0 There are 32 bits per uint, so having 8 of them essentially acts as a field of 256 boolean values, which loosely corresponds with the Keys enum type, so I assume that the static values act as a way to test which buttons are present on a device. However, XNA supports up to 4 keyboards, so I'm not sure how it both translates this to a button state, nor how it can differentiate between different keyboards in this way.


Creating a Custom Map Editor using XNA and Windows Forms I'm looking to create my own level editor for a game I'm making, and I came across the following post Tutorial or Example of creating custom sprite tool map editor for XNA? In the example posted by Blau, I am unsure what needs to be replaced in this line, and with what XnaControlGame.CreateAndShow lt MainDialog, VoxelEditorGame gt ( ) If anyone could help at all, that would be great!


achieve transparent object How can i achieve transparency and shadowing for a model in XNA ? Do you have a good tutorial ? For the shadow i can manage the effect but how can i implement the transparency also ? Do i have to use the pass in effects ? And if so, how can i make an object transparent ?