using odd number of sprites in multi row spriteSheet? Using XNA it's pretty easier to loop through a sprite sheet, I tell it how many rows and how many columns it has and I have a method that loops through the whole set. I usually use this method in my sprite class, but I have a sprite sheet that has a odd number of sprites, and does not use the entire last line. Any ideas on how to do this? for example I have 3 rows of 6 columns, but on the last row I only have 3 sprites. Thanks!


Measuring GPU time from managed code To measure CPU code, I use a Stopwatch. Using a Stopwatch in the Draw method is meaningless for the GPU side of things since the CPU and the GPU run asynchronously. The questions is simple Is it possible to measure the total time spent on a chunk of HLSL code? Perhaps as granular as the technique pass.


Figuring out which direction my object is facing on a 2D plane? My friend and I were messing around in XNA 4.0 making a 2D racing game. Kind of like this one Ivan Ironman Stewart s Super Off Road. The problem we are having is knowing which direction the car is facing to move it appropriately. We could track the direction by a enum value North, South, East, West but we don't want to do that for a number of reasons. We were wondering if there was a way to accomplish this via math. Maybe by having an anchor point designated at the hood of the car and having the car always move towards that spot and then move that anchor point. We aren't sure. Or maybe there is a way using a 2D Vector. I figured since we hit a hard spot, we should ask the coding community for help! Just to be clear. I'm not looking for code I just want to discuss some concepts of 2D movement in all directions without having to track a direction enum. I know that can't be the only way to do it.


HLSL Manual Alpha Blending I'm trying to do alpha blending manually because I only want to apply alpha blending on certain pixels. Underlying is the texture I'm writing to. This is what I got so far, but it doesn't give the same result as when AlphaBlendEnable TRUE What formula does default alpha blend in HLSL use? matrix WorldViewProjection texture2D OverlyingShadingMap sampler2D OverlyingShadingMapSampler sampler state texture lt OverlyingShadingMap gt texture2D UnderlyingShadingMap sampler2D UnderlyingShadingMapSampler sampler state texture lt UnderlyingShadingMap gt struct VertexShaderOutput float4 Position SV POSITION float4 Color COLOR0 float2 TextureCoordinates TEXCOORD0 VertexShaderOutput SpriteVertexShader(float4 position POSITION0, float4 color COLOR0, float2 texCoord TEXCOORD0) VertexShaderOutput output output.Position mul(position, WorldViewProjection) output.Color color output.TextureCoordinates texCoord return output float4 SpritePixelShader(VertexShaderOutput input) COLOR float4 overlying tex2D(OverlyingShadingMapSampler, input.TextureCoordinates) clip(overlying.a 0.001) float4 underlying tex2D(UnderlyingShadingMapSampler, input.TextureCoordinates) Alphablending float3 rgb overlying.rgb overlying.a (1 overlying.a) underlying.a underlying.rgb float alpha underlying.a (1 underlying.a) overlying.a return float4(rgb, alpha) technique SpriteDrawing pass P0 AlphaBlendEnable FALSE VertexShader compile vs 2 0 SpriteVertexShader() PixelShader compile ps 2 0 SpritePixelShader()


Does every Entity in an XNA game need it's own BasicEffect instance? From what I see, the position matrix is stored in the BasicEffect instance, so it makes sense to me that every object has it's own position matrix, but I'm not 100 sure it's correct to let every Entity have it's own BasicEffect instance, so I'm asking here.


Handling lost graphics device XNA 4.0 in winforms I'm trying to put in a new feature into my level editor. Part of the feature is to bring up a form when a user places a new tile onto the map, but once the form is brought up the XNA embedded screen throws up a big red X. I think this is due to the embedded screen losing focus to the form and then crashing. This is where the form is initialized public Form1() InitializeComponent() Node Editor tileDisplay1.OnInitialize new EventHandler(tileDisplay1 OnInitialize) tileDisplay1.OnDraw new EventHandler(tileDisplay1 OnDraw) Microsoft.Xna.Framework.Input.Keys allKeys (Microsoft.Xna.Framework.Input.Keys ) Enum.GetValues(typeof(Microsoft.Xna.Framework.Input.Keys)) foreach (var key in allKeys) KeyboardInput.AddKey(key) KeyboardInput.KeyRelease new KeyHandler(KeyboardInput KeyRelease) MouseInput.MouseMove new MouseMoveHandler(MouseInput MouseMove) MouseInput.MouseDown new MouseClickHandler(MouseInput MouseDown) MouseInput.MouseUp new MouseClickHandler(MouseInput MouseUp) Application.Idle delegate tileDisplay1.Invalidate() saveFileDialog1.Filter "Map File .map" Mouse.WindowHandle tileDisplay1.Handle This is where the draw event is fired off void tileDisplay1 OnDraw(object sender, EventArgs e) Logic() Render() KeyboardInput.Update() MouseInput.Update() foreach (var actor in Actor.Actors) actor.Update() This is where the form is being called private void Logic() if (colIndex 8 amp amp AssociateBox.SelectedIndex 0) currentCollisionLayer.SetCellIndex(collideCellX, collideCellY,form.spawnNumber.ToString()) if(form.spawnNumber "12") camdetails.ShowDialog()


Where do I place XNA content pipeline references? I am relatively new to XNA, and have started to delve into the use of the content pipeline. I have already figured out that tricky issue of adding a game library containing classes for any type of .xml file I want to read. Here's the issue. I am trying to handle the reading of all XML content through use of an XMLHandler object that uses the intermediate deserializer. Any time reading of such data is required, the appropriate method within this object would be called. So, as a simple example, something like this would occur when a character levels public Spell LevelUp(int levelAchived) XMLHandler.FindSkillsForLevel(levelAchived) This method would then read the proper .xml file, sending back the spell for the character to learn. However, the XMLHandler is having issues even being created. I cannot get it to use the using namespace of Microsoft.Xna.Framework.Content.Pipeline. I get an error on my using statement in the XMLHandler class using Microsoft.Xna.Framework.Content.Pipeline.Serialization.Intermediate The error is a typical reference error Type or namespace name "'Pipeline' does not exist in the namespace 'Microsoft.Xna.Framework.Content' (are you missing an assembly reference?)" I THINK this is because this namespace is already referenced in my game's content. I would really have no issue placing this object within my game's content (since that is ALL it deals with anyways), but the Content project does not seem capable of holding anything but content files. In summary, I need to use the Intermediate Deserializer in my main project's logic, but, as far as I can make out, I can't safely reference the associated namespace for it outside of the game's content. I'm not a terribly well versed programmer, so I may be just missing some big detail I've never learned here. How can I make this object accessible for all projects within the solution? I will gladly post more information if needed!


Side detection on Rectangle collision detection? How can I determine which of the sides on a Rectangle that was hit by another Rectangle (or Circle if that's easier)? I originally tried creating 8 subrectangles for my main rectangle one for each side and corner with the appropriate length and width of one pixel. This didn't work out very well though, to my understanding it was thwarted by the speed and update frequency... Any thoughts?


XNA and HLSL shaders Instancing using World Matrix array I have posted this question on StackOverflow and was directed here, so I'll just copy the question I am attempting to improvise some sort of hardware instancing in my game. I wish to draw multiple trees with only one Draw Call. So far, I have set up a class which holds the model, texture, and an array of Matrices. Each matrix corresponds to a location of one tree in the game world. I have determined to use 50 copies of object as hard coded limit within my class and my shader. I am sure that the matrices generated are correct ones. Using Basic effect with multiple draw calls and switching out World matrices between them does yield in correct number of trees on their correct locations. I have tried a shot in the dark approach float4x4 View float4x4 Projection float4x4 World 50 ... VertexShaderOutput VertexShaderFunction(VertexShaderInput input) VertexShaderOutput output 50 for (int i 0 i lt 50 i ) float4 worldPosition mul(input.Position, World i ) float4 viewPosition mul(worldPosition, View) output i .Position mul(viewPosition, Projection) output i .texCoord input.texCoord return output i To my surprise, this actually did compile, and to even greater surprise, didn't melt my GPU. To not so big of a surprise, this draws only one tree, the first one, as the loop ends as soon as it hits the "return" keyword as any sane mind would expect it to. I have tried my google fu skills with googling this kind of problem, but majority of the results deal with C code (I'm using C XNA), and their approach to the problem is basically to collect all needed model's vertices and forward all that, as one huge model drawn with one World matrix position. Is there a reliable way to draw one model using an array of World matrices on a shader, or must I collect all vertex data and batch it that way? P.S. I am attempting to toy around with nested structures, like these struct VertexShaderOutput float4 Position POSITION0 float2 texCoord TEXCOORD0 struct VSOUT VertexShaderOutput output 50 VSOUT VertexShaderFunction(VertexShaderInput input) VSOUT output for (int i 0 i lt 50 i ) float4 worldPosition mul(input.Position, World i ) float4 viewPosition mul(worldPosition, View) output.output i .Position mul(viewPosition, Projection) output.output i .texCoord input.texCoord return output But, of course, as the loop gets unrolled, the very next instance of Output gives an overlapping semantic error. I am pretty sure there are no POSITION50 and TEXCOORD50 semantics p So, how would I go about solving this problem? Thank you in advance!


How many update and draw calls can a windows phone suppport I'm making a Windows Phone game (XNA 4.0) which requires a lot of activity on the screen. It's working well for now. But what I am concerned about is that it uses a lot of sprites and many of them as 'lists' so that I can make multiple copies of the sprite, and this causes a lot of Update() calls which have 'for' loops and collision testing method calls also. This also increases the number of Draw() calls. As the game progresses, I am going to need to add more sprites and update calls. Can that cause problems in Windows Phone? (Currently I have no device to test it on). My game has 18 sprites for now and most of them requires multiple copies to be drawn on screen. Is there a more efficient way to achieve this?


Concerning The Minecraft Skybox I was wondering how does the stars in night time in minecraft work, are they point sprites? And are they placed on a texture or just randomly placed on some far away location. EDIT 1 OK, well, with the imformation gathered concerning the minecraft skybox I now know that the stars are not directly textured onto a sphere but are individial quads placed some set distance (the radius of the sphere) from the player. The problem is now I will I go about getting a random position on that sphere (not in it and not too far out of it). And how will I get rotation for it to face the player? One user suggested normalising a random Vector3 then multiplying it by the spheres radius which I think, simply won't work. Also another suggested that I use the formular "1 x 2 y 2 z 2", I don't know how I would use this to find a random position on a sphere either. EDIT 2 OK, I haven't tested this or anything but from all the imformation gathered from PrinceCharles anwser it should be something like this float x (float)random.NextDouble() 2 1 float y (float)random.NextDouble() 2 1 float z (float)Math.Sqrt((double)(1f x x y y)) Vector3 randomPoint new Vector3(x, y, z) if (randomPoint.Length() ! 0) randomPoint.Normalize() Vector3 pointOnSphere randomPoint radius Position Rotation stars.Add(new Star(pointOnSphere, new Vector3(0, 0, 0))) The reason for the " 2 1" is to give the random a range of 1 to 1. I think that is correct... EDIT 3 One side of the map The other Any ideas? Thanks )


Drawing transparent and opaque 3D objects. How do I preventing z fighting? I am using a transparent weighted average algorithm to draw my transparent objects. The transparent object is drawn with the following notable render states (the rest are default XNA values) CustomBlendState.Additive, DepthStencilState.DepthRead, RasterizerState.CullNone, SamplerState.PointClamp The opaque object is drawn using the following states BlendState.Opaque DepthStencilState.Default RasterizerState.CullCounterClockwise SamplerState.PointClamp In the picture below there is what I believe is a z fighting issue where the green block and the wooden block meet. How can I keep the objects in the same location and stop this issue from occurring? When changing the transparent object's DepthStencilState.DepthRead state to DepthStencilState.None the issue goes away. While this is what led me to believe it was a z fighting issue, the opaque object will then no longer occlude the transparent object when viewed from another angle. EDIT Applying a depth bias to the situation makes no discernible difference either public static RasterizerState SolidNoCullBias new RasterizerState() CullMode CullMode.None, FillMode FillMode.Solid, DepthBias 1f, SlopeScaleDepthBias 1f, EDIT 2 Culling the triangles will cause the object to look incorrect as a transparent object should show both the inside and outside faces. EDIT 3 Depth Stencil State is as follows with 'LessEqual' compare function (doesn't solve the issue)


Lerping to a center point while in motion I have an enemy that initially flies in a circular motion, while facing away from the center point. This is how I achieve that position.Y (float)(Math.Cos(timeAlive MathHelper.PiOver4) radius origin.Y) position.X (float)(Math.Sin(timeAlive MathHelper.PiOver4) radius origin.X) if (timeAlive lt 5) angle (float)Math.Atan((0 position.X) (0 position.Y)) if (0 lt position.Y) RotationMatrix Matrix.CreateRotationX(MathHelper.PiOver2) Matrix.CreateRotationZ( 1 angle) else RotationMatrix Matrix.CreateRotationX(MathHelper.PiOver2) Matrix.CreateRotationZ(MathHelper.Pi angle) That part works just fine. After five seconds of this, I want the enemy to turn inward, facing the center point. However, I've been trying to lerp to that point, since I don't want it to simply jump to the new rotation. Here's my code for trying to do that else float newAngle 1 (float)Math.Atan((0 position.X) (0 position.Y)) angle MathHelper.Lerp(angle, newAngle, (float)gameTime.ElapsedGameTime.Milliseconds 1000) if (0 lt position.Y) RotationMatrix Matrix.CreateRotationX(MathHelper.PiOver2) Matrix.CreateRotationZ(MathHelper.Pi angle) else RotationMatrix Matrix.CreateRotationX(MathHelper.PiOver2) Matrix.CreateRotationZ( 1 angle) That doesn't work so fine. It seems like it's going to at first, but then it just sort of skips around. How can I achieve what I want here?


XNA Silverlight 5 3D Model Position I am use to XNA and starting to learn XNA for Silverlight 5. My Question is that in XNA when you create a Model and load it using content.load you are able to access the models Position, scale etc.. In Silverlight XNA these options are not available. It would be possible to change the Models position using World Translate, but I need the models position for collision detectection using boundingSphere Any Advice??


How do I make Windows store recognize multiple resolutions? I'm currently developing a XNA Game for Windows phone 8, it works with every emulator resolution (WXGA, WVGA, 720p). However, when I upload the XAP to the Windows phone store it tells me that only WVGA resolution was detected. Do I have to add some code to make the app downloadable for WXGA phone owners ?


Stacking Drawing Matrix for SpriteBatch in XNA I'm trying to make a 2D engine for XNA with SpriteBatch. My object unit is Entity, which can include other Entities as its children. However, when drawing them, the rotation and scaling stacking do not work well. Here is my Entity code protected virtual void PreDraw(Engine pEngine) pEngine.PushMatrix() Transform Matrix Translate pEngine.DrawingMatrix Matrix.CreateTranslation(this.X, this.Y, 0) Scale float translateX this.ScaleCenterY this.X float translateY this.ScaleCenterX this.Y pEngine.DrawingMatrix Matrix.CreateTranslation( translateX, translateY, 0) pEngine.DrawingMatrix Matrix.CreateScale(this.ScaleX, this.ScaleY, 0) pEngine.DrawingMatrix Matrix.CreateTranslation(translateX, translateY, 0) Rotation float translateX this.RotationCenterX this.X float translateY this.RotationCenterY this.Y pEngine.DrawingMatrix Matrix.CreateTranslation( translateX, translateY, 0) pEngine.DrawingMatrix Matrix.CreateRotationZ(MathHelper.ToRadians(this.Rotation)) pEngine.DrawingMatrix Matrix.CreateTranslation(translateX, translateY, 0) protected virtual void Draw(Engine pEngine) protected virtual void PostDraw(Engine pEngine) pEngine.PopMatrix() I will implement some primitive entities by overridding Draw method. Here is my Drawing call, and the Draw implementation for Rectangle, and the StartDrawing in the Engine Managed Draw call every drawing public void ManagedDraw(Engine pEngine) if (!this.Visible) return Perform Drawing this.PreDraw(pEngine) int childIndex 0 Underlay Children while (childIndex lt this.Children.Count amp amp this.Children childIndex .Z lt 0) this.Children childIndex .ManagedDraw(pEngine) childIndex Draw Self this.Draw(pEngine) Overlay Children for ( childIndex lt this.Children.Count childIndex ) this.Children childIndex .ManagedDraw(pEngine) this.PostDraw(pEngine) Draw implementation of Rectable protected override void Draw(Engine pEngine) pEngine.StartDrawing() pEngine.SpriteBatch.Draw(pEngine.RectangleTexture, new Rectangle(0, 0, (int)this.Width, (int)this.Height), new Rectangle(0, 0, 1, 1), this.Color) pEngine.StopDrawing() Start Drawing of Engine public void StartDrawing() this.SpriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, null, null, this.DrawingMatrix) Here is one example of my failure, where the parent has Rotation of 30, while the children has none, but it should be in the center of the parent (red) rectangle Please give me the problem with above Drawing Matrix. What should I do to achieve the stacking?


How to create simple acceleration in a 2D sprite? So here's what I thought might work but half the time I press the 'Right' key, it results in a crash and the rest of the time seems to produce no acceleration at all. if (KeyboardState.IsKeyDown(Keys.Right)) while (motion.X lt 1) motion.X 0.001f motion.X I want to know why exactly it won't work, and any possible alternate algorithms.


Problems making my basketball bounce around horizontally This is probably a very easy question, but I can't seem to understand why it's not working. I want the basketball to bounce horizontally when it touches the borders on the right and left, but when it bounces on the right, it seems to go just a little bit further than it should. Any suggestions? protected override void Update(GameTime gameTime) Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back ButtonState.Pressed) this.Exit() basketballPosition.X ballSpeed if (basketballPosition.X gt Window.ClientBounds.Width basketball.Width basketballPosition.X lt 0) ballSpeed 1 base.Update(gameTime) And my Draw method protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.CornflowerBlue) spriteBatch.Begin() spriteBatch.Draw(basketball, basketballPosition, null, Color.White, 0, Vector2.Zero, 1.5f, SpriteEffects.None, 0) spriteBatch.End() base.Draw(gameTime) Edit The problem was I was using a scale of 1.5f for drawing the image. Can someone explain how I would get the true border of the image if I were using scale? It seems the border stay as the original size, but the texture is drawn to whatever scale I choose.


How to setup Authentication Database and Game Database? I'm playing around with creating a game in C using the XNA Framework. I've decided to use technologies that I'm pretty much familiar with and create things from scratch. There are probably frameworks out there that would take away all of the difficulties that I'm encountering but I find it fun to dive into these challenges and over come them manually if you will. My current issue is that when I play MMO type games I know the general setup. I must login (authenticate) and then select a server to begin playing on. Once I log into the server I'm generally met with a Character Select screen of some sort before I actually "log in to the game". With that said, my initial attempt at developing a database system was this Authentication Database table for user information, table for server information Game Database table for characters, table for inventories, items, etc... After I created these I noticed a key missing problem. Users are linked to characters and characters are linked to a server. I currently have these pieces of information spread over 2 databases. I thought to myself, maybe this isn't a good idea? I guess I could Game Client can store the reference to the account identifier in the code once login was successful, but doesn't that sound like a security issue? Anyone have thoughts or suggestions? Or a good book recommendation for development in this area? Note I'm not trying to develop an absolute perfect system that I can release and make money off of. I'm more doing this for experience, fun and enjoyment so my solution doesn't have to be perfect, but I don't want it to be the worst possible solution either )


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?


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.


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?


Is it more efficient to use an A algorithm or a line system drawn in pathfinding in C ? I was recently introduced to the A algorithm when I asked a friend about making AI NPC's in video games move to certain points and it sounded very interesting. I am building an FPS and it has AI that must be able to move to certain points, so the A algorithm sounds very appealing to me. However, as I went through the Half Life 2 Episode 1 Developer Commentary, I found another solution that the workers at Valve have been using a line system. I couldn't find a screenshot and alas, I couldn't find the developer node to show the system. ( Basically, there's a whole system drawn on the level map for AI to move along. If there happens to be an enemy that shows up in a certain section that might not be on the AI's line of sight, then the AI can break out of the line and attack said enemy. I'm building the game in C (XNA) and I wanted to know if it would be better to use the algorithm, the line system or even both to achieve pathfinding?


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)


Shadows moving with camera. I'm using MJP's Cascade Shadow Map code and I'm having major issues with the shadows moving with the camera. Here a video to demonstrate what's going on. Also, is there a way to fix the dueling frustum issue? It's annoying seeing them pop in and out of corners of the screen. Video of the shadows c and shader code


XNA draw 3d graphics in 2d game I am programming a simple pool game in XNA. I am using Farseer for simple 2d physics but I want to use 3d graphics. My problem is I can't get the rendering to work. I have one model for the ball and one for the table, both exported from Cinema 4D into .fbx. I am able to load them and even display them, but not on the correct position. Farseer is using standart coordinate system (X to the right, Y down) and I need to somehow convert the position from farseer and display the models on the right place on the screen and with the correct size (this should be easy to achieve using scale matrix). I need help finding what my projection, view, and world matrices I should use?


Changing the texture filtering methodology within the same SpriteBatch Begin End pair How would I go about using changing the texture filtering method being used within the same SpriteBatch Begin End pairing? I have this code so far. spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null, null) spriteBatch.Draw(PixelArtTexture, new Vector2(x, y), null, Color.White, 0f, Vector2.Zero, new Vector2(8, 8), SpriteEffects.None, 0f) spriteBatch.End () This draws a pixel art texture using point filtering, however I want to draw another texture using linear filtering, so how would I do that?


Scaling textures with nearest neighbour without having to use seperate sprite batches I'm interested in being to scale textures up via nearest neighbour. I can do this via a SpriteBatch.Draw() overload however this means that any other sprites drawn within that batch will also have the scaling. What happens if I have 50 objects I want to to scale, and another 50 objects I don't want to be drawn using nearest neighbour. Assuming they alternate depths, that's 100 calls to to spriteBatch.End() in order to get depth drawn correctly. Now also let's say each object has it's own texture. One way is to you use Texture2D.SetData() to manually scale up the textures but this could get messy, very quickly. Any tips?


MonoGame Mac installation instructions Does anyone know how to install MonoGame on Mac. I have been looking around for a while and I can't find any guides. I have Mono and MonoDevelop up and running fine, but I cannot figure out how to install MonoGame. Thanks.


How to import the .fbx scene with multiple objects in XNA so that the objects retain their scene position? I have a scene that contains mutiple objects. How can I import it in XNA and maintain each object position? Right now I export the scene in .fbx and load it in a model like this cube.model contentManager.Load lt Model gt ("cub") But the objects don't retain their position and are all gathered in one point. I need a method to import all the objects as individual objects but to retain the objects position in the scene. (i.e. I need to import the scene so that I may manipulate the objects and retain their position in the scene so that I shouldn't reposition all the objects by myself) The objects are not connected, thus there are no bones. They are individual objects, just placed in some positions. This is my drawing function, the cube is the gameobject. void DrawGameObject(GameObject gameobject) foreach (ModelMesh mesh in gameobject.model.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.EnableDefaultLighting() effect.PreferPerPixelLighting true Matrix b Matrix.Identity effect.World b gameobject.orientation effect.Projection camera.projectionMatrix effect.View camera.viewMatrix mesh.Draw()


Getting more particles in engine I followed rbwhitakers tutorial on making a particle engine and I'm wondering how to get more particles on the screen. I was thinking that the "total" variable would do it but it doesnt. Is this something I'm doing wrong in the method or a hardware problem? private Particle GenerateNewParticle() Texture2D texture textures random.Next(textures.Count) Vector2 position EmitterLocation Vector2 velocity new Vector2(0, 10) float angle 0 float angularVelocity 0 Color color Color.LightSkyBlue float size (float)random.NextDouble() int ttl 100 return new Particle(texture, position, velocity, angle, angularVelocity, color, size, ttl) public void Update() int total 100 for (int i 0 i lt total i ) particles.Add(GenerateNewParticle()) for (int particle 0 particle lt particles.Count particle ) particles particle .Update() if (particles particle .TTL lt 0 particles particle .Position.Y gt 550) particles.RemoveAt(particle) particle Im creating rain but I want it to be really heavy rain. Right now it just looks like a heavy sprinkle...I guess I would call it. particleEngine.EmitterLocation new Vector2((float)rand.NextDouble() (graphics.GraphicsDevice.Viewport.Width), 0)


XNA shader compiler error in release mode I'm having a hard time figuring out if I'm doing something wrong, or if there is a bug with Visual Studio. I want to pass a float into my pixel shader, clamp it to a value, and then return it as part of the color. Here is my shader code float test float4 PixelShaderFunction(float2 texCoords TEXCOORD0) COLOR0 float n clamp(test, 0, 1) float4 color float4(n, n, n, 1) return color technique Technique1 pass Pass1 PixelShader compile ps 2 0 PixelShaderFunction() Here is how I'm using the shader protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.CornflowerBlue) simpleEffect.Parameters "test" .SetValue( 1f) spriteBatch.Begin(SpriteSortMode.Immediate, null, null, null, null, simpleEffect) spriteBatch.Draw(pixelTexture, new Rectangle(10, 10, 100, 100), Color.Red) spriteBatch.End() base.Draw(gameTime) The shader compiles fine when Visual Studio is set to Debug mode, but when I set it to Release, it gives me the following error (Please excuse the ShaderModel3Bug solution name... I get the same error with both shader model 2 and 3) Error 1 Errors compiling E C ShaderModel3Bug ShaderModel3Bug ShaderModel3BugContent simple.fx (15,23) ID3DXEffectCompiler CompileEffect There was an error compiling expression ID3DXEffectCompiler Compilation failed E C ShaderModel3Bug ShaderModel3Bug ShaderModel3BugContent simple.fx 15 23 ShaderModel3Bug Line 15 of the shader is this PixelShader compile ps 2 0 PixelShaderFunction() I have tried compiling the shader directly using fxc.exe that comes with the June 2010 DirectX SDK. Using the command fxc.exe T fx 2 0 E C ShaderModel3Bug ShaderModel3Bug ShaderModel3BugContent simple.fx Fc output.fxc, I get Microsoft (R) Direct3D Shader Compiler 9.29.952.3111 Copyright (C) Microsoft Corporation 2002 2009. All rights reserved. compilation succeeded see C Program Files (x86) Microsoft DirectX SDK (June 2010) Utilities bin x64 output.fxc So my question is, why can't Visual Studio compile the .fx file in Release mode? Am I doing something I shouldn't be doing? Update Apparently XNA Game Studio doesn't use the latest version of fxc. I downloaded the March 2009 DirectX SDK, and the compilation fails with the same generic error message as Visual Studio C Program Files (x86) Microsoft DirectX SDK (March 2009) Utilities bin x64 ps.fx(16,23) ID3DXEffectCompiler CompileEffect There was an error compiling expression ID3DXEffectCompiler Compilation failed compilation failed no code produced If I run the March 2009 version of fxc.exe with the Op (disable preshaders) flag, it compiles successfully... I am still not sure what version of fxc xna uses, or what I need to do to get my shader to compile in release mode. Any help would be appreciated.


How to design the scenarios in a platform game? I am developing a 3D platform game like Metroid Fusion with XNA. I have many classes for different elements as models, game screens, post processing and so on. Now I want to start designing the scenarios but I think that the scenarios needed in a platform game are not as conventional. I am very lost and do not know where to start and how to structure it.


XNA Game arhitecture, sharing vertices between objects I'm practicing primitives rendering in XNA and I want to create something like pipe or tunnel. I have base class called PipeSegment from which I inherit classes like RotatingSegment and NormalSegment (and whatever I imagine). To combine this segments I have created class called Pipe, which have List of PipeSegment objects.This is what I have so far It's ok, except the fact that I'm generating way more vertices than necessary. For each segment I'm generating 36 vertices for 'front side', and 36 for 'back side'. Illustration Now, my question. How can I optimize this, how to generate less vertices ? Is there any way to 'share' vertices between Segments to preserve my current code structure and is my code structure suitable for this ? Thanks


XNA Networking gone totally out of sync I'm creating a multiplayer interface for a game in 2D some of my friends made, and I'm stuck with a huge latency or sync problem. I started by adapting my game to the msdn xna network tutorial and right now when I join a SystemLink network session (1 host on PC and 1 client on Xbox) I can move two players, everything is ok, but few minutes later the two machines start being totally out of synchronization. When I move one player it takes 10 or 20 seconds (increasing with TIME) to take effect on the second machine. I've tried to Create a thread which calls NetworkSession.Update() continuously as suggested on this forum, didn't worked. Call the Send() method one frame on 10, and the receive() method at each frame, didn't worked either. I've cleaned my code, flushed all buffers at each call and switched the host and client but the problem still remain... I hope you have a solution because I'm running out of ideas... Thanks SendPackets() code protected override void SendPackets() if ((NetworkSessionState)m networkSession.SessionState NetworkSessionState.Playing) Only while playing Write in the packet manager m packetWriter.Write(m packetManager.PacketToSend.ToArray(), 0, (int)m packetManager.PacketToSend.Position) m packetManager.ResetPacket() flush Sends the packets to all remote gamers foreach (NetworkGamer l netGamer in m networkSession.RemoteGamers) if (m packetWriter.Length ! 0) FirstLocalNetGamer.SendData(m packetWriter, SendDataOptions.None, l netGamer) m packetWriter.Flush() m m packetWriter.Seek(0, 0) ReceivePackets() code public override void ReceivePackets() base.ReceivePackets() if ((NetworkSessionState)m networkSession.SessionState NetworkSessionState.Playing) Only while playing if (m networkSession.LocalGamers.Count gt 0) Verify that there's at least one local gamer foreach (LocalNetworkGamer l localGamer in m networkSession.LocalGamers) every LocalNetworkGamer must read to flush their stream Keep reading while packets are available. NetworkGamer l oldSender null while (l localGamer.IsDataAvailable) Read a single packet, even if we are the host, we must read to clear the queue NetworkGamer l newSender l localGamer.ReceiveData(m packetReader, out l newSender) if (l newSender ! l oldSender) if ((!l newSender.IsLocal) amp amp (l localGamer FirstLocalNetGamer)) Parsing PacketReader to MemoryStream m packetManager.Receive(new MemoryStream(m packetReader.ReadBytes(m packetReader.Length))) l oldSender l newSender m packetReader.BaseStream.Flush() m packetReader.BaseStream.Seek(0, SeekOrigin.Begin) m packetManager.ParsePackets()


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?


Building a shape out of two rectangles I would like to build a body with Farseer out of two rectangles so it looks like this I am a real beginner, so please describe it carefully. Thanks in advance!


XNA 4.0 Mixing 3D and 2D SpriteBatch putting weird alpha texture over whole scene I am working on a game in XNA 4.0 that has been entirely in 3D so far but now I want to incorporate a HUD. I have tried doing a simple test using spriteBatch as such spriteBatch.Begin() spriteBatch.Draw(Player.Texture, new Rectangle(0, GameConstants.GraphicsDevice.Viewport.Height 50, 50, 50), Color.White) spriteBatch.End() This works fine and the test texture shows as a rectangle in the correct position but the 3d World behind seems to have a sort of "haze" over the top which looks like the drawn "Player.Texture" has been put all over the viewport but at an alpha of like 0.1f. I googled around and have a reset() function to change some of the GraphicsDevice properties back after drawing the SpriteBatch but nothing has changed and I haven't seen anyone else with this problem. I thought it would be that SpriteBatch changes the blendmode to additive but in my reset() function I set the blendmode to opaque so I have no idea where this strange effect is coming from, it looks like I've ran some post processing on the whole scene. If I change the Player.Texture that is drawn in the SpriteBatch then the "haze" changes to look like the new texture so it is definitely to do with that. Are there any other GraphicsDevice propterties I should check to change back? Edit Okay, I have just realised the "haze" over the top is from the SkySphere texture, I am using the MSDN skysphere shader from this tutorial. So when I comment out the SkySphere code, the spritebatch and 3d drawing looks completely fine, but this leaves me with the problem that I can't have a SkySphere anymore. Is there some reason why the skysphere is sort of drawn over the scene translucently rather than behind the 3D after I use a SpriteBatch? As I said before, it kind of looks like additive blending. Below are 2 screenshots, the top is with spritebatch and no skysphere, below is with spritebatch and skysphere where I am having problems. I have cropped the images down to save upload (my internet is pretty slow at the moment) and I've changed the area of the scene in the 2nd image to show more clearly what it looks like. As I move around the scene with the camera the "haze" overlay stays in the same place exactly as how the SkySphere works, as in not taking into account the world matrix.


Why use textures that are Power of Two? Possible Duplicate Why are textures always square powers of two? What if they aren t? I am using C and XNA (also MonoGame for other platforms than Windows) to create a game in 2D. Ususally for all textures I use the NVidia plugin for Photoshop to create DDS files with precomputed mip maps (either full color, or DXT 5). How important is it, nowadays, to stick to textures with extensions that are a power of two? What are the advantages and disadvantages of doing so? The background of my question for that I use a number of quite large background images in with 1980 x 1080 pixels in size and storing them in textures of 2048 x 2048 pixels size seems like a tremendous waste of memory. Let me stress that I am aware that having only power of two textures has been important in the past for certain specific optimizations BUT I would like to know whether this TODAY (GPUs of the last 2 years, current consoles etc.) is still required?


XNA 4 game for both profiles I am writing game in XNA 4 and this version have two profiles hi def and reach. My problem is that I need to have my game code for each of these profiles and is very uncomfortable to have two projects and do all changes in both of them. My idea was to use preprocessor directive (i am not sure about name of this, http msdn.microsoft.com en us library ed8yd1ha 28v vs.71 29.aspx) and use IF statement at places with problems with profile. There is only problem that program needs to be compiled two times (for each profile) and manually changed directive and project settings to another profile. And my questions are Is that good way? Is there better and cleaner way how to do this?


Ball Physics Smoothing the final bounces as the ball comes to rest I've come against another issue in my little bouncing ball game. My ball is bouncing around fine except for the last moments when it is about to come to rest. The movement of the ball is smooth for the main part but, towards the end, the ball jerks for a while as it settles on the bottom of the screen. I can understand why this is happening but I can't seem to smooth it. I'd be grateful for any advice that can be offered. My update code is public void Update() Apply gravity if we're not already on the ground if(Position.Y lt GraphicsViewport.Height Texture.Height) Velocity Physics.Gravity.Force Velocity Physics.Air.Resistance Position Velocity if (Position.X lt 0 Position.X gt GraphicsViewport.Width Texture.Width) We've hit a vertical (side) boundary Apply friction Velocity Physics.Surfaces.Concrete Invert velocity Velocity.X Velocity.X Position.X Position.X Velocity.X if (Position.Y lt 0 Position.Y gt GraphicsViewport.Height Texture.Height) We've hit a horizontal boundary Apply friction Velocity Physics.Surfaces.Grass Invert Velocity Velocity.Y Velocity.Y Position.Y Position.Y Velocity.Y Perhaps I should also point out that Gravity, Resistance Grass and Concrete are all of the type Vector2.


XNA Automatic Collision detection from model? This is going to be a rather vague question xD In XNA is there a way of working out if a point or rectangle is colliding with a 3D .x object? It is a big model, and would take a long time to map out all the rectangles for collision detection so I was wondering if there was a easier way of doing it )


Skip processing individual triangles or vertices of the mesh In my game I have a billiard table, and a floor below the table. In typical situation the table covers 80 of the screen, so only small amount of the floor is visible. And I render the table first, so invisible part of the floor is discarded by the depth buffer test. But profiling with Nsight shows me drawing the floor takes significant amount of time, and it is spent in the rasterizer. It seems generating all those pixels of the floor and depth testing them takes a long time. I'm wondering how to solve this problem and one thing I tried is to divide the floor (a rectangle with two triangles) to multiple rectangles, so some of them could be cancelled in an earlier stage. The problem is, this is still one model mesh, just with more triangles and I don't know how to start. What would be a way to achieve this in Monogame HLSL? Somewhere in vertex shader? Or gemoetry shader (is it supported in monogame?) Or is there any other way to optimize this? UPDATE the whole floor is needed and might be drawn depending on where the camera is, so I can't get rid of parts of it. In typical situations table top covers 80 of the screen because of perspective and looking down at an angle. The game is in 3D.


is it possible to use c GUI toolbox in an XNA app? I need both reach GUI features of c toolboxes and fast rendering features of XNA, is there any way to merge these two into one app? or is there any other way? for example some equivalent to c toolbox in xna?


Avoid the same code several times in game state enum I use a switch with enums to divide my game in different parts. In the code below, that is simplified, I have a problem, becasue I need to show the same text in two or perhaps more parts and I wonder if there is a better way to do this, to avoid the use of the same code at several cases? switch (currentGameState) case GameState.Start Code break case GameState.Info Code break case GameState.PlayGame spriteBatch.Begin() spriteBatch.DrawString(scoreFont, "Score " currentScore, new Vector2(10, 10), Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 1) spriteBatch.DrawString(timeFont, "Time " secondsToDisplay, new Vector2(10, 30), Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 1) spriteBatch.DrawString(timeFont, "Spaceship " numberOfSpaceship, new Vector2(10, 50), Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 1) spriteBatch.End() break case GameState.NewSpaceship spriteBatch.Begin() spriteBatch.DrawString(scoreFont, "Score " currentScore, new Vector2(10, 10), Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 1) spriteBatch.DrawString(timeFont, "Time " secondsToDisplay, new Vector2(10, 30), Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 1) spriteBatch.DrawString(timeFont, "Spaceship " numberOfSpaceship, new Vector2(10, 50), Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 1) spriteBatch.End() break case GameState.GameOver Code break


Why do I get an exception when accessing my sprite members in this fashion? I'm getting a NullReferenceException error on the line where I do new Vector2(...). I think the problem is with the variables I'm using even though they're working to control the player sprite, so surely they can't be null, right? That is, however, in a different class and is initialized at the top of this one. Here is the method in question public void Shoot() if bullet delay resets then shoot if (bulletDelay gt 0) bulletDelay if bullet delay is 0 then create a bullet at player bulletPosition if (bulletDelay lt 0) Here I create the new bullet passing in the texture and then modifying the bulletPosition were the bullet will appear from bullets newBullet new bullets() bulletPosition new Vector2(mySprite.imgX, mySprite.imgY) newBullet.isVisible true These two lines mean that you can have no more that 20 bullets on screen at once if (bulletList.Count lt 20) bulletList.Add(newBullet) reset bullet delay if (bulletDelay 0) bulletDelay 10 bulletDelay is so the player can't spam the shoot button and have it be too easy. I tried to add a breakpoint on that line, when I run the program and hit the space bar that runs the Shoot() method the program stops and tells me about the error. When I hover over though it still says they are null. I had the instances of the classes in the following code below. I've changed it so they are in the Shoot() method and all seems to well however I'm curious as to why the below code wasn't the correct way to do it public void Initialize() mySprite new PlayerSprite() bulletList new List lt bullets gt ()


Using 2d collision with 3d objects I'm planning to write a fairly basic scrolling shoot 'em up, however, I have run into a query with regards to checking for collision. I plan to have a fixed top down view, where the player and enemies are all 3d objects on a fixed plane, and when the enemy or player fires at the other, their shots will also be along this fixed plane. In order to handle the collision, I have read up a bit on collision detection in 3d, as it is not something I have looked into previously, but I'm not sure what would be ideal for this situation. My options appear to be Sphere collision, however, this lacks the pixel precision I would like Detection using all vertexes and planes of each object, but this seems overly convoluted for a fixed plane of play Rendering the play screen in black and white (where white is an object, black is empty space), once for enemies and once for the player, and checking for collisions that way (if a pixel is white on both, there is a collision) Which of these would be the best approach, or is there another option that I am missing? I have done this previously using 2d sprites, however I can't use the same thinking here as I don't have the image to refer to. Edit For clarity, I just wanted to add some additional information. One of the things that I would like to account for is if the player or enemy is rotated in some way, which would mean intersecting along 1 Z plane would not be completely accurate. For example, if there is banking on the player's ship when they move from side to side, the tips of their ship would be above and below the central plane, but I would still like these parts to be possible to hit. Secondly, I plan to have different sizes and shapes for the player's craft, where the size and shape affects the hit box and is one of the properties the player can use to choose which ship they would like to use.


XNA SoundEffect with offset I've been trying to make a soundmanager recently which has several functions which fits my needs. But one thing I can't solve, is the offsetting the soundeffects. Is it possible to play a soundeffect from a specific point? I know I have to use the buffering, but I couldn't find anything on the net about it. Any help would be appreciated!


XNA DrawIndexedPrimitives or DrawUserIndexedPrimitives? When rendering primitives in XNA, does it matter if I use DrawIndexedPrimitives() versus DrawUserIndexedPrimitives()? RB Whitaker uses the former, while Reimer's uses the latter. From what I can tell, the intent is that if you're using a premade type that ships with XNA (such as VertexPositionNormalTexture), you should use the normal draw primitives function, while if you create a custom struct which satisfies IVertexType and or VertexDeclaration, you should use the DrawUserPrimitives instead. However, XNA places no such restriction on how they're used, and I am wondering why it wasn't just all rolled into one generic function to begin with.


Why is BayazitDecomposer inaccessible when upgrading from Farseer 3.3.1 to Farseer 3.5? I used the following code in Farseer 3.3.1 and it worked correctly, but in Farseer 3.5, I always get an error message in the following line list BayazitDecomposer.ConvexPartition(textureVertices) 'FarseerPhysics.Common.Decomposition.BayazitDecomposer' is inaccessible due to its protection level What is wrong? Why is the code not working with Farseer 3.5? How can I use the decomposition tools in Farseer 3.5?


Removing something on Collision? I have my collision detection code working so how would I tell my HealthPickup to disappear when my Player collides with it? I haven't played around with it yet but I think I may have to somehow remove the hitbox and stop calling the Draw() function (at least for my HealthPickup anyway) Please note I am a novice and have not really dealt with XNA before.


SpriteBatch does not draw on graphicDevice I'm using a control which is using XNA inside. But when I try to draw something, it doesn't appear. I already did a lot of tests but can't figure out what's wrong. Here is the test I set up RenderTarget2D rTarget new RenderTarget2D(GraphicsDevice, 1000, 1000) GraphicsDevice.SetRenderTarget(rTarget) GraphicsDevice.Clear(Color.White) spriteBatch.Draw(ts.Texture, layer.Location, source, Color.White, layer.Angle (float)Math.PI 180, origin, SpriteEffects.None, 1f) int spriteBatchGraphics spriteBatch.GraphicsDevice.GetHashCode() int normalGraphics GraphicsDevice.GetHashCode() GraphicsDevice.SetRenderTarget(null) using (FileStream stream new FileStream("pic.png", FileMode.Create)) rTarget.SaveAsPng(stream, 1000, 1000) using (FileStream stream new FileStream("pic2.png", FileMode.Create)) ts.Texture.SaveAsPng(stream, ts.Texture.Width, ts.Texture.Height) SpriteBatch.Begin, End and GraphicDevice.Present is called too. Because I didn't see anything, I tried to draw the stuff onto a renderTarget and save it to the HDD. I also saved the texture itself to be sure it's not just white. However, spriteBatch should draw a 48x48 block here and I checked the parameters of spriteBatch, they are okay. But on the rendertarget, nothing appears. I reacts on GraphicDevice.Clear, the color I pick there really gets drawn. The hashCodes of both graphicDevices are the same, so they really seem to draw to the same device. What could cause this? EDIT I searched for some more and I found the following I'm getting a AccessViolationException when closing the program. First I thought it's unrelated but it seems it's caused by what happened before. I found in the internet that a very bad graphic card can cause this. And the graphic card I tried this on was very bad indeed. So I tried it on an other machine now I'm getting different results, but it's still not working and I'm still getting the exception. Here is what it draws now In place of the black spot, the tile should be drawn. But it's not happening. The AccessViolationException only happens when the draw glitch happens in this case as soon it just draws a black block instead the real texture. The lines are planed and part of it (the horizontal are still missing for some reason, but trying to fix that later). So what is happening? Gets the graphic device too much stressed? I'm also running a game class which runs with the default loop (which manages the winforms and game). I absolutely need the XNA technology here, because it should "preview" something from the game and using System.Drawing could change the outcome. The program also could get used by clients so a normal powered graphic card should be able to deal with it.


Why do I get an error about being unable to change rasterizer states in this code? I'm trying to toggle between wireframe and full mode while drawing a 3d model. So far I have this rs new RasterizerState() In my update method if (state.IsKeyDown(Keys.V)) rs.FillMode FillMode.WireFrame if (state.IsKeyDown(Keys.C)) rs.FillMode FillMode.Solid and in my draw method GraphicsDevice.RasterizerState rs But I get the error Cannot change read only RasterizerState. State objects become read only the first time they are bound to a GraphicsDevice. To change property values, create a new RasterizerState instance. What am I doing wrong here?


My sprites are spwaning on top of each other with a new class? I am making a game for college in XNA C , however I have got to the point where I need some enemy sprites to be spawned in for the player to shoot. I did this with one enemy by itself without using arrays and for loops to load and update all the enemy's at once as I have my enemy sprites inside a class. The class I have it supposed to give the enemy a random position, load the texture in and then draw them. So I thought I would put my enemy sprites in a form of a array, and use a for loop to load, update and draw them. However, it all works but they all spawn in the random position on top of each other, but this works with one enemy at a time without for loops or putting them in an array. Here is some of the code I used This is how I decide how many enemy sprite I want. giantManager giant new giantManager 7 Because I have to create an instants of the giantManager class before the load content I use this to do so for (int i 0 i lt 7 i ) giant i new giantManager() The following is how I load the giantManager class with the texture for my giants in the load function for (int i 0 i lt 7 i ) giant i new giantManager(Content.Load lt Texture2D gt ("giant")) Then to draw them I just use for (int i 0 i lt giant.Length 1 i ) giant i .Draw(spriteBatch) And this is the draw method inside the class public void Draw(SpriteBatch spriteBatch) spriteBatch.Draw(giantTexture, new Rectangle((int)position.X, (int)position.Y, giantTexture.Width, giantTexture.Height), null, Color.White, giantAngle, new Vector2(giantTexture.Width 2, giantTexture.Height 2), SpriteEffects.None, 0) To choose my random spawn location I just use the Random C data type and use if statements to decide which spawn location to set depending on the Random number generated. This happens in the constructor here public giantManager(Texture2D newTexture) giantTexture newTexture position randomPosition() Just to conclude this question I would like to say sorry if I have posted to much code or not explained it in enough detail, I have tried by best. Also if you look at this image below, it shows the rectangles in a black box, now the player rectangle is a little see through, but the giant rectangle is totally black which is because they all spawn on top of each other. That is my problem. Thanks for reading all of this and any help in advanced would be great.


Atmospheric scattering sky from space artifacts I am in the process of implementing atmospheric scattering of a planets from space. I have been using Sean O'Neil's shaders from http http.developer.nvidia.com GPUGems2 gpugems2 chapter16.html as a starting point. I have pretty much the same problem related to fCameraAngle except with SkyFromSpace shader as opposed to GroundFromSpace shader as here http www.gamedev.net topic 621187 sean oneils atmospheric scattering I get strange artifacts with sky from space shader when not using fCameraAngle 1 in the inner loop. What is the cause of these artifacts? The artifacts disappear when fCameraAngle is limtied to 1. I also seem to lack the hue that is present in O'Neil's sandbox (http sponeil.net downloads.htm) Camera position X 0, Y 0, Z 500. GroundFromSpace on the left, SkyFromSpace on the right. Camera position X 500, Y 500, Z 500. GroundFromSpace on the left, SkyFromSpace on the right. I've found that the camera angle seems to handled very differently depending the source In the original shaders the camera angle in SkyFromSpaceShader is calculated as float fCameraAngle dot(v3Ray, v3SamplePoint) fHeight Whereas in ground from space shader the camera angle is calculated as float fCameraAngle dot( v3Ray, v3Pos) length(v3Pos) However, various sources online tinker with negating the ray. Why is this? Here is a C Windows.Forms project that demonstrates the problem and that I've used to generate the images https github.com ollipekka AtmosphericScatteringTest Update I have found out from the ScatterCPU project found on O'Neil's site that the camera ray is negated when the camera is above the point being shaded so that the scattering is calculated from point to the camera. Changing the ray direction indeed does remove artifacts, but introduces other problems as illustrated here Furthermore, in the ScatterCPU project, O'Neil guards against situations where optical depth for light is less than zero float fLightDepth Scale(fLightAngle, fScaleDepth) if (fLightDepth lt float.Epsilon) continue As pointed out in the comments, along with these new artifacts this still leaves the question, what is wrong with the images where camera is positioned at 500, 500, 500? It feels like the halo is focused on completely wrong part of the planet. One would expect that the light would be closer to the spot where the sun should hits the planet, rather than where it changes from day to night. The github project has been updated to reflect changes in this update.


Moving along a flat plane with accordance to camera view I'm making a 3D game, and I'm stuck on a little experiment. I currently have a flat plane with a free camera running around, and a sphere (really, a light approximated as a sphere) that rests above the surface of the plane at, say, 50 units up. I'm trying to move the sphere, and I can do this easily by simply adding to the position in the X and Z direction. However, I got a bit messed up because when I move the camera, pressing the left arrow might move the sphere to the right, because of the coordinates. So I'm trying to move the sphere along the X and Z dependant on where my camera is looking. For example, if I was looking at it from behind, down on an angle, I expect the sphere to move to the camera's left along the plane, or move down towards the camera, still along the plane. I have seemed to get left and right working with a.Position Vector3.Cross(((FreeCamera)camera).Forward, ((FreeCamera)camera).Up) but trying to move the sphere using just the camera's forward causes the sphere to move into or out of the plane, depending on the angle of the camera (this makes sense, because the camera's forward may be pointing into the plane). My question is, how do I move an object left or right along a plane (remaining 50 units above the Y axis) in accordance to the camera's direction? For example, viewing the plane from its left facing towards the center, moving left should make it move towards the top of the plane if viewed from the back or to the camera's local left. Here's two screenshots showing what I mean When viewing the red light from here Pressing right should give me this. Notice how the red sphere has moved (disregard the fact the camera angle changed slightly)


Problem displaying model I downloaded the FBX of this free model http www.turbosquid.com FullPreview Index.cfm ID 485548 Yet when i try and display it in my project foreach (ModelMesh mesh in player.Meshes) foreach (BasicEffect beffect in mesh.Effects) beffect.View view beffect.Projection projection beffect.EnableDefaultLighting() mesh.Draw() I end up with the teeth of the model way out from the body, and the eyes expanded so large they stick out the sides of the model. Could someone tell me what i am doing wrong? Or is the model the issue?


Can someone explain this Pulsate code to me Pulsate the size of the selected menu entry. double time gametime.TotalGameTime.TotalSeconds float pulsate (float)Math.Sin(time 6) 1 scale new Scale(1 pulsate 0.05f,1 pulsate 0.05f) I grabbed it from the XNA GameState sample and just curious.


UI mockups to the code My UI designer has made a lovely photoshop PSD of the UI and everything pretty. The biggest problem I'm having is converting some of the more elegant fonts used into something renderable in game. Is there a way to convert these font styles in Photoshop to a bitmap font of some sort? I need to be able to render text like this inside my code


Highlight edge on 3d cube in directx I want to make a 3d editor in DX9 XNA for a project I'm working on. I'm just thinking through how I would go about certain tasks and I'm stuck on one particular thing, which is crucial to making the editor working. The editor will allow 3d objects to be added to the scene. For example I would add a cube to the scene. Now I want to be able to select one edge of the cube. When this edge is selected it should change colour. The remaining edges should not change colour. If my description is not clear enough then it would basically be the same as the edge tool in blender. If you look at the following image you will see the first double cube has its centre edge highlighted http wiki.blender.org index.php File Manual Part II EdgeSpecials EdgeSlide.png I can't recall coming across anything in DX9 or XNA that allows edges to highlighted in this way. Would this be done in a shader perhaps? Thanks Edit From OP (Can't seem to post comments so editing the original.) I had considered drawing lines but wasn't sure if it would trace the exact same path as the edge. I guess I it would be best to try this first before dismissing it. The purpose of the post was to find out if xna or dx9 had something built into it to do this sort of thing. I'm currently just in the design phase so have not implemented anything. I would accept the answer from Roy T but I can't find the option to do so! Thanks.


XNA ignoring the Z coordinate? XNA seems to be ignoring my Z coordinate. There is no form of Z culling at all it seems. How come? I am doing an orthographic projection, and clearing the depth stencil buffer for every draw call. My elements rendered are quads with textures, through instancing. These elements have 1 difference in the Z coordinate in order to eachother, based on theri Z index.


how to load normals for a model from texture2d? I know i can do this through custom shaders, but i want to know is it possible to set it through xna itself. As for each effect i have pick normals from a texture2d, i want to change normals of model. I have done this much, but i don't know how to go further?? foreach (ModelMesh mesh in Home.Model.Meshes) if (mesh.Name meshName) foreach (ModelMeshPart part in mesh.MeshParts) VertexPositionNormalTexture normals new VertexPositionNormalTexture part.VertexBuffer.VertexCount part.VertexBuffer.GetData lt VertexPositionNormalTexture gt (normals) Color data new Color normalMap.Height normalMap.Width normalMap.GetData lt Color gt (data) Thank you


MonoGame WP custom vertex decleration How do I go about implementing and using a custom vertex deceleration in monogame for windows phone 8. I want to be able to store a position, a colour and a normal?


Player's camera, how to obtain smooth movement In a 2D platformer, I have a player that can move both horizontally and vertically. I also have a camera that moves in relation to player. In every update I do this public void RepositionCamera() For the example I don't consider world rectangle bounds current camera.Position new Vector2( player .Position.X 250, player .Position.Y 100)) The problem here is that when I press very rapidly "left right left rigth..." the camera does a very annoying effect, it seems an eartquake. I think this is due to the strict relation to player's position and camera's position. This is just an example, it is annoying also when climbing onto stairs because every step I force the player's Y up to the step height, so the camera does the same thing! How can I solve this? How can I edit my RepositionCamera() to be less strict about moving itself?


Developing for Chrome App Android? I have been developing for win7 mobile (XNA silverlight and will continue to do so, love everything about it) but I wanted to branch a few of my more polished games to google app store online, and perhaps android(though not sure, as with all the different versions it makes learning loading applications a bit tricky) What is the most versatile language to start learning from chrome apps android Java would be excellent for android, but could I port it to a web app for chrome? (and its close to C ) Flash would work for a web app as I can just embed it into a html page (have done actionscript before, didn't care much for the IDE though), but would it also work on android? or I guess there is always C C but haven't heard much about that, though I think it works for both (though C does interest me) Any advice would be excellent, thanks.


MonoGame Left Right Sided Collision Not Working I'm working on a platformer as part of my course, the problem I have come across is Left Right sided collision is not working very well. I already have bottom amp top collision working. Here is an example of the problem in action As you can see pretty much all the time I'm slowing down, I know this issue but haven't found a work around code solution yet. The main problem I'm having as you can see is my player being able to slide almost into the middle of the block if he's coming down and moves into the block. The slow down problem is due to my left right collision code, I just haven't found a viable solution yet for sided collision. Collision Code foreach (SkyTile block in PlatformBlocks) IntersectRectangle block.GetRect() GetRect().Intersects(ref IntersectRectangle, out IntersectResult) if (GetRect().Intersects(block.GetRect())) if (IntersectResult amp amp (IntersectRectangle.Bottom gt GetRect().Bottom)) isPlatformColliding true if (IntersectResult amp amp (IntersectRectangle.Top lt GetRect().Top)) isPlatformBottomColliding true if (IntersectResult amp amp (IntersectRectangle.Left gt GetRect().Left)) isPlatformLeftColliding true if (IntersectResult amp amp (IntersectRectangle.Right lt GetRect().Right)) isPlatformRightColliding true break if (isPlatformColliding) velocity.Y 0 if (isPlatformBottomColliding amp amp !isPlatformColliding) velocity.Y 20 if (isPlatformLeftColliding) velocity.X 0 if (isPlatformRightColliding) velocity.X 0


How can multiple clients be out of sync if they use the same RNG seed? I have been working on a client server architecture to enable LAN play for my open source game, Aigilas. In its current state, players stay synced in all running instances of the game but enemies and particle animations are out of sync. What I cannot understand is how players are the only entities staying synced. I run the clients in lockstep, requiring the latest input states from each client to be announced before taking a turn in the game world. When the game world is built, I seed the random number generator (RNG) with a seed determined by the server. This seed appears to affect the RNG as expected each client has the same procedurally generated game world and players start in all clients at the appropriate locations. Particle animations and AI are chosen based on player positions and the RNG. How is it possible for them to become out of sync when the players are always in sync? To the best of my observations of both the game screen and the logs, players never go out of sync with respect to their positions. That leads me to believe that the RNG in C is not acting deterministically across all clients. The basic workflow for the game's client lt server communications are as follows Server starts Client starts and gets RNG seed from server Client tells server when keys are pressed depressed by a user Once a game has started, server tells all clients the current state of each player's keyboards Once an update has been received from the server, one turn of the game is simulated Repeat step 4 If there are any specific questions targeting a specific portion of the code, then I am happy link to the appropriate page on GitHub.


Rotation based on movement How can i calculate angle based on movement in C XNA when i'm moving object with accelerometer? If object is moving up, sprite would rotate in corresponding direction. Should i use two vector coordinates(old, new) to calculate angle using Atan2?


How to go from Texture2DContent to Texture2D in a content processor? I'm using reflection to create a manifest of all assets, strongly typed. It's working fine for my own types I get the type of the asset, if a processor is ran on it I get the output type. Then I check to see if there's a ContentSerializerRuntimeTypeAttribute applied to the type. If so, then I get the RuntimeType value and do a Type.GetType() to get the type back. The problem I have is if the type is Texture2DContent (for example) as that doesn't have the ContentSerializerRuntimeTypeAttribute. How can I go from a Type representing Texture2DContent to a Type representing Texture2D? I know I can just check for EndsWith("Content") as a last resort, but how to I get the namespace qualified type so I can get my Type object?


How do you keep the gameplay and music in sync in a rhythm game? What's the best way to program a rhythm based game in XNA? (Some sort of game like Dance Dance Revolution) Would you use the built in GameTime? What logic would you use to make sure the game constantly stays in sync to the music? Any tips would be much appreciated! What I am basically asking is how you would keep the gameplay in sync with the music. For example in DDR how would I correctly sync the arrows to the beat of the music?


XNA Framework HiDef profile requires TextureFilter to be Point when using texture format Vector4 Beginner question. Synopsis my water effects does something that causes the drawing of my sky sphere to throw an exeption when run in full screen. The exception is XNA Framework HiDef profile requires TextureFilter to be Point when using texture format Vector4. This happens both when I start in full screen directly or switch to full screen from windowed. It does NOT happen, however, if I comment out the drawing of my water. So, what in my water effect can possibly cause the drawing of my sky sphere to choke???


What is wrong with my vertex declaration? What is wrong with my vertex declaration below? I am using it with instancing. After adding TextureInformation to it, it renders weird and has an epileptical seizure. public struct VertexInstance IVertexType public Matrix World public Color Color public Vector3 TextureInformation I use arithmetic here to show clearly where these numbers come from You can just type 28 if you want public static readonly int SizeInBytes sizeof(float) 23 Vertex Element array for our struct above public static readonly VertexElement VertexElements new VertexElement(0, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 0), new VertexElement(sizeof(float) 4, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 1), new VertexElement(sizeof(float) 8, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 2), new VertexElement(sizeof(float) 12, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 3), new VertexElement(sizeof(float) 16, VertexElementFormat.Color, VertexElementUsage.TextureCoordinate, 4), new VertexElement(sizeof(float) 20, VertexElementFormat.Vector3, VertexElementUsage.TextureCoordinate, 5) public static VertexDeclaration Declaration get return new VertexDeclaration(VertexElements) VertexDeclaration IVertexType.VertexDeclaration get return new VertexDeclaration(VertexElements)


How can I move an object diagonally on Windows Phone? I want to pull a sprite from point A(vector2) to point B(vector2) in my Windows Phone XNA game. GestureType.HorizontalDrag moves it horizontally and GestureType.VerticalDrag moves it vertically, how can I move the sprite diagonally? The player should be able to pull the sprite in every direction if he touches the sprite with his finger. The sprite can't be moved if the player's finger isn't on the sprite. How can I do that? How can I move an object diagonally on Windows Phone?


What is the best way to follow this book using XNA 4.0 instead of XNA 2.0 I found a reference to this book on the Microsofot Indie games forums http www.amazon.com dp 1430209798 ref pe 385040 30332200 pe 309540 26725410 item I'm really interested in it, because the example project is very close to the style of gameplay I'm looking for in my next game. The downside is, I was hoping to write the game in XNA 4.0 and maybe even Monogame. Would the best option here be to just follow along with the book using xna 2.0, and then try to rewrite update the app in xna 4 or monogame? Or, would it be better to start my project as an XNA 4.0 project, and then code along with the book, fixing any discrepancies as I come across them?


Setting effects variables in XNA I am currently reading a book named "3D Graphics with XNA Game Studio 4.0" by Sean James and have some questions to ask If i create a effect parameter named lets say SpecularPower and have in my effect a variable named SpecularPower , if i do something like effect.Parameters "SpecularPower" .SetValue(3) That wil change the SpecularPower variable in my effect ? And a second question, not regarding the book If i have a spaceship and i've created a "boost" functionality that speeds up my spaceship, what effects should i implement to create the impresion oh high speed ? I was thinking of making everything except my spaceship blurry but i think there would be something missing . Any ideas ? Regards, Alex Badescu


GetData() error creating framebuffer I'm currently porting a game written in C with XNA library to Android with Monogame. I have a Texture2D and i'm trying to get an array of uint in this way Texture2d textureDeform game.Content.Load lt Texture2D gt ("Texture terrain") uint pixelDeformData new uint textureDeform.Width textureDeform.Height textureDeform.GetData(pixelDeformData, 0, textureDeform.Width textureDeform.Height) I get the following exception System.Exception Error creating framebuffer Zero at Microsoft.Xna.Framework.Graphics.Texture2D.GetTextureData (Int32 ThreadPriorityLevel) 0x00000 in 0 I found that the problem is in private byte GetTextureData(int ThreadPriorityLevel) creating the framebuffer private byte GetTextureData(int ThreadPriorityLevel) int framebufferId 1 int renderBufferID 1 GL.GenFramebuffers(1, ref framebufferId) framebufferId is still 1 , why can't be created? GraphicsExtensions.CheckGLError() GL.BindFramebuffer(All.Framebuffer, framebufferId) GraphicsExtensions.CheckGLError() renderBufferIDs new int currentRenderTargets GL.GenRenderbuffers(1, ref renderBufferID) GraphicsExtensions.CheckGLError() attach the texture to FBO color attachment point GL.FramebufferTexture2D(All.Framebuffer, All.ColorAttachment0, All.Texture2D, this.glTexture, 0) GraphicsExtensions.CheckGLError() create a renderbuffer object to store depth info GL.BindRenderbuffer(All.Renderbuffer, renderBufferID) GraphicsExtensions.CheckGLError() GL.RenderbufferStorage(All.Renderbuffer, All.DepthComponent24Oes, Width, Height) GraphicsExtensions.CheckGLError() attach the renderbuffer to depth attachment point GL.FramebufferRenderbuffer(All.Framebuffer, All.DepthAttachment, All.Renderbuffer, renderBufferID) GraphicsExtensions.CheckGLError() All status GL.CheckFramebufferStatus(All.Framebuffer) if (status ! All.FramebufferComplete) throw new Exception("Error creating framebuffer " status) ... The frameBufferId is still 1, seems that framebuffer could not be generated and I don't know why. Any help would be appreciated, thank you in advance.


how are the vertex properties of meshpart decided based on model format in xna Exactly how the question says , how does the vertex properties like vertex stride and the data stored in the mesh part decided based on the format of a model and how would i determine that and then decide which vertexdeclaration to be used properly For ex a .obj model might or might not have vt data , vn data based on which it may have a different data in the meshpart . How would i go about deciding which vertex declaration to use to properly decode the data in that mesh's vertex buffer


Does SoundEffect.CreateInstance load from file everytime? This is something which has been bugging me. If I create a SoundEffectInstance via SoundEffect.CreateInstance() I'm meant to dispose of it when I'm finished with it. SoundEffect.CreateInstance() does not use ContentManager as far as i can tell. So does it load from file or does it keep a copy in memory? Loading from file would obviously be very slow


ContentManager in XNA cant find any XML Im making a game in XNA 4 and this is the first time I'm using the Content loader to initialize a simple class with a XML file, but no matter how many guide I follow, or how simple or complicated is my XML File the ContentManager cant find the file the Debug keep telling me "A first chance exception of type 'Microsoft.Xna.Framework.Content.ContentLoadException' occurred in Microsoft.Xna.Framework.dll". I'm really confuse because I can load SpriteFonts and Texture2D without a problem ... I create the following XML (the most basic Xna XML) lt ?xml version "1.0" encoding "utf 8" ? gt lt XnaContent gt lt Asset Type "System.String" gt Hello lt Asset gt lt XnaContent gt and I try to load it in the LoadContent method in my main class like this System.String hello Content.Load lt System.String gt ("NewXmlFile") There is something I'm doing wrong? I really appreciate your help


Shuffle tiles position in the beginning of the game XNA Csharp I'm trying to create a puzzle game where you move tiles to certain positions to make a whole image. I need help with randomizing the tiles start position so that they don't create the whole image at the beginning. There is also something wrong with my offset, that's why it's set to (0,0). I know my code is not good, but I'm just starting to learn. My start up tile positioning code spriteBatch new SpriteBatch(GraphicsDevice) PictureTexture Content.Load lt Texture2D gt ( "Images bildgraff") FrameTexture Content.Load lt Texture2D gt ( "Images framer") Laddar in varje liten bild av den stora bilden i en array for (int x 0 x lt 4 x ) for (int y 0 y lt 4 y ) Vector2 position new Vector2(x pictureWidth, y pictureHeight) position position Offset Rectangle square new Rectangle(x pictureWidth, y pictureHeight, pictureWidth, pictureHeight) Square frame new Square(position, PictureTexture, square, Offset, index) squareArray x, y frame index For reference, here is the square class class Square public Vector2 position public Texture2D grafTexture public Rectangle square public Vector2 offset public int index public Square(Vector2 position, Texture2D grafTexture, Rectangle square, Vector2 offset, int index) this.position position this.grafTexture grafTexture this.square square this.offset offset this.index index public void Draw(SpriteBatch spritebatch) spritebatch.Draw(grafTexture, position, square, Color.White) public void RandomPosition() public void Swap(Vector2 Goal ) if (Goal.X gt position.X) position.X position.X 144 else if (Goal.X lt position.X) position.X position.X 144 else if (Goal.Y lt position.Y) position.Y position.Y 95 else if (Goal.Y gt position.Y) position.Y position.Y 95


Emit light from items In order to create a day night cycle in my game, I decreased the r,g and b values of the Color variable after a certain amount of time has passed. This worked as expected. I am wondering in order to create light from an item, like a fire or lamp, could I create a circle around the item and set the color in that circle to be white? Or is there a better way for accomplishing this in 2d?


XNA Darkening background and drawing something on top In a game a group of friends and I are working on using XNA, we wanted to create an effect where we could darken the screen and draw something else on top of the darkened portion. For example, we have a title screen that is drawn as a background sprite, a logo, a few buttons, and a lot of particle effects (all separate Texture2D's), but when you select the "Exit" button, the entire title screen darkens, and two (undarkened) buttons are drawn over top ("exit" and "cancel" buttons). Initially, we were going to do this by having two separate render targets, one for the title screen, and one for the yes and no buttons. Then, when we wanted to display the topmost render target, we darkened the render target that the title screen was drawn to, and then draw the new render target on top. The problem with this is that the second render target is filled with black pixels that simply get drawn over the background, blocking it out completely. We have two ideas to fix this. The first idea is to draw the second render target on top of the first using BlendState.Additive, so that the black pixels are simply added to the background instead of drawn over top. The problem with this is that it makes the other buttons look weird, since they're being drawn over top other things on the title screen. The second idea was to manually set every black pixel in the second render target to Color.Transparent, but we're not sure how efficient that is. Any ideas on how we could achieve this effect?


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 Xbox, utilizing multiple cores Possible Duplicate XNA How does threading work? It's my understanding that the Xbox has 3 cores that are available to use. I'm hoping to offload AI to another core, and possibly use another core to see if certain objects are on screen(if so they will be added to a list to be drawn). How would I go about doing this? It needs to be compatible on the xbox360.


Finding the monitors orientation in XNA for Windows Just to be clear this is not for Windows Phone 7. ) I've got some interesting requirements for a project and I'm having trouble trying to find the information I need. I have two monitors. The default monitor is landscape. The second monitor is portrait. Right now I save the width and height and then change Graphics.PreferredBackBufferWidth and Graphics.PreferredBackBufferHeight to the values returned from GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width (1920) and GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height (1080) right before toggling to full screen. This works fine on the monitor in landscape mode. The monitor in portrait however scales 1920x1080 to fit onto the 1080x1920 screen. I'm looking for either a way to determine that the monitor is in portrait mode or have the CurrentDisplayMode.Width and CurrentDisplayMode.Height return the portrait appropriate values. I've been rifling through the XNA Framework documentation and googling like mad and not finding anything helpful.


Strange anomalies when using WinForms with XNA I haven't seen any questions related to my issue, and this leads me to believe I'm missing something minor, however The Problem I'm creating a game that is effectively launched from a windows form. Consider the following code. static void Main(string args) main new TestGame() The Game class. menu new Menu(main) The form. while (true) if (menu.ShowDialog() DialogResult.OK) if (menu.ShouldStartGame) main.RunGame( Some params ) else ExitGame() break This loop works fine. My issue lies in the form itself. Firstly, DialogResult does not trigger at all. When the result from menu.ShowDialog() is printed, its result is "Cancel" which is not the option set for the button (OK.) As well as this, picture boxes, the form background colour and other such controls do not work properly. And the form appears to have a UI style from Windows versions before or during XP. Is this a known issue or am I missing something?


Does passing uniform constants from technique into shader cause branches? I am trying to find a way to organize my evergrowing number of shader techniques functions (I am coding in sm 3.0). One way is to do this float4 PS Crossroads(PS INPUT input, uniform bool left right) COLOR0 if (left right) GoLeft() else GoRight() ... technique LEFT pass Pass1 VertexShader compile vs 3 0 VertSh() PixelShader compile ps 3 0 PS Crossroads(true) technique RIGHT pass Pass1 VertexShader compile vs 3 0 VertSh() PixelShader compile ps 3 0 PS Crossroads(false) My question is will this cause a branch at runtime or will the compiler be smart enough to split it into two separate techniques? Thanks. P.S. Ok I won't post this as answer, because we already have an answer by someone much more experienced than me, but from my humble tests (on different PCs) and my humble Google research, this approach (using uniform constants) is efficient and indeed forces the compiler to create different shader versions for each branch, removing flow controll completely from the finall compiled shader. I tested the compiled shader codes with Nvidia NSight.


Is there any way to enable the HiDef graphics profile property on a Silverlight 5 3d Web App? I have an XNA Windows Game that uses the HiDef profile to load complex fbx and obj files. Trying to move it over to a Silverlight 3d Web App, Silverlight seems to only want to use the Reach profile, and I get an error that the Reach profile does not support a sufficient number of primitive draws per call. Is there any way to change to HiDef in Silverlight 5? It is not in the project properties and attempting to change it in mainpage.xaml.cs only gives me the option of setting it to Reach.


Can someone explain this occurrence with a fbx model in xna? Because this is kind of weird to explain, let's show you what I mean. This is in my game. When I import this base ship model, it should be at (1000,1000,1000), but the model acts like it's at (1000,1000, 0). Note it is positioned correctly when I use a .x model. So it has to be the model. I need to know what's wrong with it. Here is the model file, tell me if anything is wrong with it https dl.dropbox.com u 92848165 station2.FBX http i.imgur.com VsjH8.jpg EDIT The model works if you import it into Google Sketchup...but you lose the textures, not very nice.


Can I release Kinect based games? I've been reading up some hacks on Kinect development to work around the fact that there is no official SDK from Microsoft. Even if we do manage to create a game, can we distribute it through the XBox marketplace? Or will it cause any issues?


Function for sun movement? So, given a sun sprite set at the horizon (x 0, y worldheight 2) I'm trying to devise a function to make the sun rise, then fall. The best way to do this would be the sin function, but I have no idea how to use it. if using y sin(x), then x would have to range between 0 and pi for a full curve, while having a constant velocity for X. Any thoughts or suggestions? Edit Thanks guys!


How to correctly handle multiple Songs in XNA? I'm working on a (Windows only) game in XNA, and I have multiple music tracks. I don't want to load them all into memory, but play them on demand. To properly dispose them, I have a separate ContentManager just for music and a method that looks like this public void PlayMusic(MusicTracks trackToPlay) if (trackToPlay currentlyPlayingTrack) return MediaPlayer.Stop() musicContentManager.Unload() Song song null switch (trackToPlay) case MusicTracks.TitleMusic song musicContentManager.Load lt Song gt ("TitleMusic") break case MusicTracks.CreditsMusic song musicContentManager.Load lt Song gt ("CreditsMusic") break if(song ! null) MediaPlayer.Play(song) MediaPlayer.IsRepeating true currentlyPlayingTrack trackToPlay (MusicTracks is an enum). Is this the correct way to make sure I'm not using more RAM Resources than required? Or should I be looking into XACT? To be clear, I don't need to play multiple Songs at the same time (I do need to play 1 Song and a few SoundEffects though) and I don't need any crazy effects apart from setting the Volume of the music independently from the soundeffects, which should be straight forward with MediaPlayer.Volume.


How can I use a 3x3 matrix within a 4x4 matrix representation? In XNA there is only one Matrix class which is actually 4x4 matrix. How to use it to represent a 3x3 matrix? I am trying to represent the inertia tensor of a body which is a 3x3 matrix, so I have data for only a 3x3 matrix. How can I store that in a 4x4 matrix and still have operations on it be valid?


Separate game clocks intervals in XNA I am making a real time strategy game in XNA. I have separated the Client (rendering, input, sound) code from the Sim (game logic). I want to have features like replaying and fast forwarding. Also, I would like to give the Sim longer time intervals in its Update to finish its work without having to always implement time slicing to prevent frame rate stuttering. I imagine I can do this when the two systems become decoupled and have their own update frequency. So, how can I run the Client and Sim at two different update intervals? How should I code it? Currently I am running with FixedTimeStep false and using ElapsedGameTime in Update() computations. Can I create new GameTime instances to leverage this existing code..?


How to rotate (YAW) aircraft in XNA? I'm developing a flight simulator based on Riemer's Blog tutorial (XNA C ). To control the aircraft, I use the following code Quaternion additionalRotation Quaternion.Identity additionalRotation Quaternion.CreateFromAxisAngle(Vector3.Forward, roll) additionalRotation Quaternion.CreateFromAxisAngle(Vector3.Right, pitch) model ROTATION additionalRotation This only executes pitch and roll. I wanted to add code so that if the aircraft is rolling, then it should rotate to right or left (yaw) so I changed the code to the following Quaternion additionalRotation Quaternion.Identity additionalRotation Quaternion.CreateFromAxisAngle(Vector3.Forward,roll) additionalRotation Quaternion.CreateFromAxisAngle(Vector3.Up, yaw) additionalRotation Quaternion.CreateFromAxisAngle(Vector3.Right, pitch) model ROTATION additionalRotation This behaviour is not so realistic when I roll the aircraft rotates to right left (yaws), but at the same time it loses altitude and I must pitch up (pull handle) to avoid crashing. Is there any solution to make slew rotation (yaw) without losing altitude.


How AlphaBlend Blendstate works in XNA 4 when accumulighting light into a RenderTarget? I am using a Deferred Rendering engine from Catalin Zima's tutorial His lighting shader returns the color of the light in the rgb channels and the specular component in the alpha channel. Here is how light gets accumulated Game.GraphicsDevice.SetRenderTarget(LightRT) Game.GraphicsDevice.Clear(Color.Transparent) Game.GraphicsDevice.BlendState BlendState.AlphaBlend Continuously draw 3d spheres with lighting pixel shader. ... Game.GraphicsDevice.BlendState BlendState.Opaque MSDN states that AlphaBlend field of the BlendState class uses the next formula for alphablending (source Blend.SourceAlpha) (destination Blend.InvSourceAlpha), where "source" is the color of the pixel returned by the shader and "destination" is the color of the pixel in the rendertarget. My question is why do my colors are accumulated correctly in the Light rendertarget even when the new pixels' alphas equal zero? As a quick sanity check I ran the following code in the light's pixel shader float specularLight 0 float4 light4 attenuation lightIntensity float4(diffuseLight.rgb,specularLight) if (light4.a 0) light4 0 return light4 This prevents lighting from getting accumulated and, subsequently, drawn on the screen. But when I do the following float specularLight 0 float4 light4 attenuation lightIntensity float4(diffuseLight.rgb,specularLight) return light4 The light is accumulated and drawn exactly where it needs to be. What am I missing? According to the formula above (source x 0) (destination x 1) should equal destination, so the "LightRT" rendertarget must not change when I draw light spheres into it! It feels like the GPU is using the Additive blend instead (source Blend.One) (destination Blend.One)