How to create a fog effect in XNA with PixelShaderFunction? I developped a small XNA games in 3D. I would like to add a "fog of war" on my models instantiated with an effect in my (.fx) file. The problem is, I do not know how to change the function "PixelShaderFunction". File .fx Here is the declaration of my variables in my effect file (.fx) InstancedModel.fx Microsoft XNA Community Game Platform Copyright (C) Microsoft Corporation. All rights reserved. Camera settings. float4x4 World float4x4 View float4x4 Projection Fog settings float FogNear float FogFar float4 FogColor And my function "PixelShaderFunction" in my effect file (.fx) Both techniques share this same pixel shader. float4 PixelShaderFunction(VertexShaderOutput input) COLOR0 return tex2D(Sampler, input.TextureCoordinate) input.Color


Collision detection of cicle and rectangle How to find the collision detection of a moving rectangle on circular object? Here i have tried to junp rectangular object but the collision detection of a small rectangular object while jumping doesnt have smooth collision detection? Can anyone please help me ?


In XNA, how do I get forms to display in front of my full screen game? I'm trying to open a form in front of my game, which is full screen. However, the form seems to appear only behind the game window. At the moment, I'm doing this protected override void Update(GameTime gameTime) if(Keyboard.GetState().IsKeyDown(Keys.Q)) graphics.IsFullScreen true graphics.ApplyChanges() new Form1().Show() The form is empty, just created. base.Update(gameTime) I can reach the form with AltTab, but this is unfriendly to the user. How can I do this correctly?


Getting the angle between two objects? I have a set of boxes which create a sort of path, they don't intersect very smoothy and to help that process I'm trying ot find a way to get an angle between them that can make it easier to generate another box between the intersection points. Here's a pic of what I mean, the crudely drawn yellow arrows are basiclaly the angles I'm trying to find to put boxes there


Texturing (or seeing through) the back of a plane I've got a basic textured quad forming a plane. When I move the camera or rotate the plane to see the back of it, there is no texture there. The effect I want is as if the plane were a clear piece of glass, so that I'd be seeing the texture from through the other side. I was hoping this was going to happen automagically. Is there an easy way to accomplish such a thing, or am I going to have to manually flip the texture and assign it to the back? Thanks!


Should Draw method calculate the element's screen location? Should Update take care of calculating the drawing position of element or should it be done exlusively in Draw method? If I calculate the drawing position of element in Update and then store it as element property then I can reuse it in Draw method. I can only run the update if the element (or camera) moved so it seems it would be good for performance. Is this good approach? Or should I never store the draw position of an element and always calculate it in Draw method? EDIT It seems my question wasn't clear enough. I'm not talking about elements Draw method but the Draw method of manager renderer that draws them on the screen. The elements themselves do not have Draw method.


Xna winform scaling and mouse position I am attempting to create a simple 2d level editor using xna and winforms. I have used the app hub win form samples as a starting point. At first I was having trouble with the mouse coordinates but after setting the mouse handle to the control, it is working fine. But now I want to implement scaling into the editor. I want the level editor to always be 720p. I have accomplished this by rendering to a render target set to 720 and then draw this using sprite batch to the back buffer. This also works great with letter boxing to keep the right ratio. I used the technique detailed here https stackoverflow.com questions 7591466 xna resize window without increasing resolution. However because of the letting boxing my mouse coordinates are now wrong again. Can someone help work out how to solve this? I tried getting the size of the letter box and subtracting that from the mouse coordinates but that didn't work. Has anyone got any suggestions?


How to change something inside an switch statement? So my question is how would you draw a list of strings, and then if a case of the enum is a certain way, then draw them a different way? Here is an example of what I mean enum CurrentState Menu1, SubMenu1, SubMenu2 private CurrentState currentState CurrentState.Menu1 public void Draw(SpriteBatch spriteBatch, GameTime gameTime) Draw list here so it is always displayed in all cases switch ( currentState) case CurrentState.Menu1 How would you erase the previous list and draw it in a different way here? break case CurrentState.SubMenu1 How would you erase the previous list and draw it in a different way here? break case CurrentState.SubMenu2 How would you erase the previous list and draw it in a different way here? break


Inconsistent accessibility error in xna Hey all, you may remember me asking a question regarding a snake game I was creating about two weeks ago. Well I'm quite far now into making the game (thanks to a brilliant tutorial I found). But I've come across the error described named above. So heres my problem I have a SnakeFood class that has a method called "Reposition". In the game1 class I have a method called "UpdateInGame" which calls the reposition method to load an orange that spawns in a random place every second. My latest piece of code changed the reposition method to allow the snake I have on the screen to not be overlapped by the orange that randomly spawns. Now I get the error (in full) Error 1 Inconsistent accessibility parameter type 'TheMathsSnakeGame.Snake' is less accessible than method 'TheMathsSnakeGame.SnakeFood.Reposition(TheMathsSnakeGame.Snake)' C Users Tom Documents Visual Studio 2008 Projects TheMathsSnakeGame TheMathsSnakeGame SnakeFood.cs 33 21 TheMathsSnakeGame I understand what the errors trying to tell me but having changed the accessiblity of the methods, I still can't get it to work. Sorry about the longwinded question. Thanks in advance ) Edit Code I'm using (Game1 Class) private void UpdateInGame(GameTime gameTime) Calls the oranges "reposition" method every second if (gameTime.TotalGameTime.Milliseconds 1000 0) orange.Reposition(sidney) sidney.Update(gameTime) (SnakeFood Class) public void Reposition(Snake snake) do position new Point(rand.Next(Grid.maxHeight), rand.Next(Grid.maxWidth)) while (snake.IsBodyOnPoint(position))


XNA Debugging Testing Individual Sprites and Pixel Collision I ran through the first training on XNA where you make a shooter game. They did some thing that I would not do and I want to use their starting point to learn more things. I want to try better collision and adding a menu. I saw something online with the sonic physics where they have a frame by frame of sonic moving 1 pixel. See picture below. I am new to development, but I have been programming for years now. What would you guys suggest to try these different things out. How would I simulate a similar frame by frame testing as they do in the above picture? Thanks!


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.


What are the semantics of these quaternion functions in XNA Monogame? I am having trouble understanding the semantics of some members of the XNA Monogame Quaternion class. The docs are not helpful, and tutorials trying to explain quaternions are using heavy math, which isn't helpful for me either, since I simply do not have proper background for that. My main questions currently are Is there any difference between Multiply and Concatenate? What is the exact difference between Inverse and Negate?


SpriteBatch Draw Using Floats with the Destination Rectangle So I created a nice little isometric tile engine and I have it so that when you scroll with the mouse it changes a variable called scale. Scale is a float and gets passed through the spritebatch.draw() function. I apply scale to all of the math I do when generating the positions of the tiles. The problem I am having is Rectangle will not accept float numbers so when I make my Dest Rectangle for the spritebatch.draw() I can not use the numbers I need to because they are now floats. I tried using vector4 instead of rectangle but the spritebatch.draw was throwing an exception saying it was expecting Rectangle not Vector4. Is it possible to draw the dest rect using floats instead of ints? Btw the scale is all working properly however since I am casting the floats to ints any scale that should have a decimal gets truncated and I end up with spaces between my tiles.


Global keyboard states I have following idea about processing keyboard input. We capture input in "main" Game class like this protected override void Update(GameTime gameTime) this.CurrentKeyboardState Keyboard.GetState() main Game class logic here base.Update(gameTime) this.PreviousKeyboardState this.CurrentKeyboardState then, reuse keyboard states (which have internal scope) in all other game components. The reasons behind this are 1) minimize keyboard processing load, and 2) reduce "pollution" of all other classes with similar keyboard state variables. Since I'm quite a noob in both game and XNA development, I would like to know if all of this sounds reasonable. UPDATE If someone is interested, actual utility class, as suggested by David Gouveia, I've created can be found here.


Getting fastest path on a grid How would I go about finding the fastest path to connect two points on a grid? I'm making a 2D game and the map is based around a grid. I need to be able to account for any blocked tiles that the path need be able to go through. Example http imgur.com BbtnR The blue line being what I need to figure out, and the red tiles being the blocked tiles. Where should I start? Any advice be would great!


Moving models with a matrix Currently I have a playerWorld matrix which holds the position of my player, just a simple sphere. When I press a key to move the model, it does some crazy thing and flies off the screen really fast, and not even in the direction I want it to go. if (kbs.IsKeyDown(Keys.W)) playerWorld Matrix.CreateTranslation(playerWorld.Forward elapsed) Why is this happening? elapsed is a float variable float elapsed (float)gameTime.ElapsedGameTime.TotalSeconds Here is the draw code, maybe it's being drawn wrong? public void Render(ThirdPersonCam cam) foreach (ModelMesh mesh in playerModel.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.View cam.view effect.Projection cam.proj effect.World playerTransforms mesh.ParentBone.Index playerWorld mesh.Draw()


2D Platform Game Jumping I'm currently writing a game in XNA for fun which uses C . I have got my sprites loaded and when the character moves right he looks like he is running right and when he moves left he looks like he is running left. I been looking everywhere for a good coding example for how to create a jumping ability. I have read all the physics stuff that I can stand and it doesn't help when I can't figure out how to use say space bar to jump yet can't keep them from using space just jump again until they land.


How to move a line of sprites in a sine wave? So, I'm spawning a horizontal line of enemies that I would like to have move in a nice wave. Currently I tried Enemy.position.X Enemy.velocity.X Enemy.position.Y (float)Math.Cos(Enemy.position.X 200) 5 This...kind of works. But the wave is not a true wave. The top and bottom of one pass are not the same (e.g. 5 for the top, and 5 for the bottom (I don't mean literal points, I just meant that it's not symmetrical)). Is there a better way to do this? I would like the whole line to move in a wave, so it looks fluid. By that, I mean that it should look like each enemy is "following" the one in front of it. The code I posted does have this fluidity to it, but like I said, it's not a perfect wave. Any ideas? Thanks in advance.


Texturing 2D vectorial terrain (or simply masking texture) I have a procedurally generated terrain, as follows It is generated and then built using Farseer Physics, however I haven't found a way to create and apply a mask to texture it properly, I have already played with stencil buffers and pixel shaders but I still have no solution at the moment. How would I do that? Am I going the right direction with stencil and pixel shader? Thank You.


What are the pros and cons of Lua vs. Python as a scripting language for XNA C platform? I am thinking about giving a go to one of my ancient ideas for a game. The core point of this game would be the possible level of functional customization of the game environment and objects (such as modifying the behavior of a space ship weaponry). For this the game would need to be scriptable. Also I don't aim to commercialize it, it is merely an interesting programming challenge for me. As I am mostly a .NET guy I will use XNA C for the game itself. For the scripting I think about going with Python or Lua. I have previous experience with Python and have nothing against it as a language. Lua on the other hand is almost completely new to me, besides some minor World of Warcraft addons modifications I did here and there, and it looks promising. So here is my question What are the pros and cons of Lua vs. Python as a scripting language for XNA C platform? Is one of them considerably easier to use with XNA C ? Has one of them some specific advantages or disadvantages when used with XNA C ? Why would you recommend one over the other for XNA C ?


Retrieving components from game objects (entities) Using C and XNA 4, I've made the decision to go for an entity component based design for my game after reading such posts as this and this, but I'm now struggling to find how to retrieve components once they've been added to an entity. Some articles I've read say that when a component is created, register it with the system that will act upon it, using a messaging system. A drawback I see here is that if a system needs 2 components to act (say CollideComponent and PositionComponent) then this gets complicated (and I can't figure how it would work). The other possibility, and the one that I'm currently pursuing, is to have a system ask whether an entity has a particular component when it needs it. However I've not seen any code examples, only theory on the net, so I've been trying to muddle it together. Some code here might explain how far I've got First a System public class RenderingSystem IGameSystem public void PerformAction(IQueryable lt IGameObject gt gameObjects) foreach (var gameObject in gameObjects) RenderableGameComponent renderableGameComponent gameObject.GetComponent lt RenderableGameComponent gt (ComponentType.Renderable) if (renderableGameComponent ! null) this.spriteBatch.Draw(renderableGameComponent.Texture, renderableGameComponent.DrawablePosition, Color.White) Now the actual GameObject public class GameObject IGameObject private List lt IGameComponent gt gameComponents private ComponentType componentTypes public void AddComponent(IGameComponent component) this.gameComponents.Add(component) this.componentTypes this.componentTypes component.ComponentType public T GetComponent lt T gt (ComponentType componentType) return (T)this.gameComponents.FirstOrDefault(gc gt gc.ComponentType componentType) And finally the Component and ComponentType enumeration public class RenderableGameComponent IGameComponent public Texture2D Texture get set public Vector2 DrawablePosition get set public ComponentType ComponentType get return ComponentType.Renderable Flags public enum ComponentType Renderable 1, Updateable 2, Position 4, Now as you might be able to see, I'm trying to use bitwise operations on the ComponentType enumeration that every Component of each GameObject has. The reason being I thought this would be a much cleaner approach when trying to get the required Component out of the GameObject when asked by a System (also refer to link 1 above). I'm trying to get away from passing in a type, and doing an iteration over all the Components of a GameObject. eg foreach (var component in this.GameComponents) if (component.GetType() requestedType) return component This is because when there are a few hundred bullets on the screen and a CollidableSystem is created, it will massively slow the game down checking every type. I've had experience with this when creating a previous game, but admittedly, that was using an inheritance based design system. It worries me that for each System that is created, it will have to iterate over every GameObject every tick asking the same question every time, "Do you have the component I am looking for ?" and still doing a lot of casting and null checks. Now my question is this. I want to know whether there is a de facto design pattern for getting Components from GameObjects that don't require null checks or casting ? Someway a System will say "Give me this component, I know that you have it" and not bother wasting time asking those GameObjects that don't have the Component. Tell, don't ask.


Matrix transforming with translation rotation scale at center of screen I'm trying to create a camera using matrix transforms, the gist is as follows Transform Matrix.CreateRotationZ(Rotation) Matrix.CreateTranslation(new Vector3( Position.X, Position.Y, 0)) Matrix.CreateScale(Zoom) Matrix.CreateTranslation(new Vector3(Bounds.Width 0.5f, Bounds.Height 0.5f, 0)) It works but with one issue. The rotation origin remains at the starting ( Position.X, Position.Y) while the zoom works fine (at the center screen) which is obvious from the code. I'd like the rotation to occur at the center screen as well.


How can I improve my isometric tile picking algorithm? I've spent the last few days researching isometric tile picking algorithms (converting screen coordinates to tile coordinates), and have obviously found a lot of the math beyond my grasp. I have come fairly close and what I have is workable, but I would like to improve on this algorithm as it's a little off and seems to pick down and to the right of the mouse pointer. I've uploaded a video to help visualize the current implementation http youtu.be EqwWcq1zuaM My isometric rendering algorithm is based on what is found at this stackoverflow question's answer, with the exception that my x and y axis' are inverted (x increased down right, while y increased up right). Here is where I am converting from screen to tiles these next few lines convert the mouse pointer position from screen coordinates to tile grid coordinates. cameraOffset captures the current mouse location and takes into consideration the camera's position on screen. System.Drawing.Point cameraOffset new System.Drawing.Point( 0, 0 ) cameraOffset.X mouseLocation.X (int)camera.Left cameraOffset.Y ( mouseLocation.Y (int)camera.Top ) the camera aware mouse coordinates are then further converted in an attempt to select only the "tile" portion of the grid tiles, instead of the entire rectangle. this algorithm gets close, but could use improvement. mouseTileLocation.X ( cameraOffset.X 2 cameraOffset.Y ) Global.TileWidth mouseTileLocation.Y ( ( 2 cameraOffset.Y cameraOffset.X ) Global.TileWidth ) Things to make note of mouseLocation is a System.Drawing.Point that represents the screen coordinates of the mouse pointer. cameraOffset is the screen position of the mouse pointer that includes the position of the game camera. mouseTileLocation is a System.Drawing.Point that is supposed to represent the tile coordinates of the mouse pointer. If you check out the above link to youtube, you'll notice that the picking algorithm is off a bit. How can I improve on this?


Platform independent replacement for LuaInterface I'm currently working on a project in C XNA, however I'm planning to migrate this to MonoGame so that it can go onto more platforms. The problem is that I am currently using a lot of Lua, and for that in XNA, I am using LuaInterface. The issue I now have is that LuaInterface only runs on Windows because of the dlls that it requires, but I would like to make this project available on Linux and Macs as well. Does anyone know of a good alternative to LuaInterface that could slot into Mono quite nicely? Re writing the parts which are currently in Lua in another language wouldn't be too much of a problem, but I need to be able to use scripting as I want to make large portions of my game open to players for modding.


How to correctly enable anti aliasing in XNA? In my project when I add graphics.PreferMultiSampling true this line in the Game1 Constructor (as the msdn website suggests), anti aliasing does not enable. Any idea what I might be missing ? Here is the full code public Game1() base() graphics new GraphicsDeviceManager(this) graphics.PreferredBackBufferWidth 720 game's width graphics.PreferredBackBufferHeight 720 game's height graphics.PreferMultiSampling true Content.RootDirectory "Content" protected override void LoadContent() spriteBatch new SpriteBatch(GraphicsDevice) LightningSegment Content.Load lt Texture2D gt ("Lightning Segment") protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.DarkCyan) Matrix skew Matrix.Identity skew.M12 (float)Math.Tan((double)Math.PI 6) spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, skew Matrix.CreateScale(1.5f, 3f, 1)) spriteBatch.Draw(LightningSegment, new Vector2(200, 200), null, Color.Red, 0, new Vector2(0f, 300f 2f), new Vector2(250f, 1f), SpriteEffects.None, 0f) spriteBatch.End() base.Draw(gameTime)


colliding 2 moving and rotating sprites in xna 2d I recently started making a game in windows phone XNA, I have a rocket in the middle that I can rotate and has a thrust to speed up in the direction it is facing and meteors coming out. The point is to survive as long as you can and avoid collision with the meteors. I can't manage to implement the collision between two moving and rotating sprites which are the rocket and a random meteor. I've seen rectangular collision which to me appears bad but maybe I am coding it a bit wrong and the pixel collision is way complicated any help would be appreciated, thanks in advance )


xna creating game stage management contrls I am under planning stage of my game where I am creating controls for my game. I have create below control for stages but have no idea how this we can achieve in xna. Please also help me with your views regarding how to load, play multiple stages and persist score for each stage in game using xna. What we normally used to do is just put everything in infinite loop but here I want more intelligence in game, as one stage over it should go back to menu. Example can be something like angry bird stages.


Grid Based 2D Lighting Problems I am aware this question has been asked before, but unfortunately I am new to the language, so the complicated explanations I've found do not help me in the least. I need a lighting engine for my game, and I've tried some procedural lighting systems. This method works the best if (light xx 1, yy gt light xx, yy ) light xx, yy light xx 1, yy lightPass if (light xx, yy 1 gt light xx, yy ) light xx, yy light xx, yy 1 lightPass if (light xx 1, yy gt light xx, yy ) light xx, yy light xx 1, yy lightPass if (light xx, yy 1 gt light xx, yy ) light xx, yy light xx, yy 1 lightPass (Subtracts adjacent values by 'lightPass' variable if they are more bright) (It's in a for() loop) This is all fine and dandy except for The system favors whatever comes first in the for() loop This is what the above code looks like applied to my game On the left side you can see some weirdness going on The loop goes top to down then to the right column This is how the for() loop goes Light provided from my mouse, should be a full light, but is only half If I could get some help on creating a new procedural or otherwise lighting system I would really appreciate it!


How do I pause an XNA game? I'm trying to implement pausing by following this tutorial. The tutorial recommends essentially this as the implementation if (!paused) Simulate(gameTime) How does this work? What does Simulate mean here?


Windows 7 8 imcompatibility via XNA? I have MS Visual Studio 2010 installed on my machine (a Windows 7 Pro 64 bit), and im developing a game in XNA 4.0 with it. I can run the program just fine from the .exe file in the bin directory, and it appears to have no bugs. But when trying it on Windows 8 64 bit, it just doesn't run. Am I doing something wrong or is XNA suddenly incompatible in this case? BTW this game has no 3d graphics at all, just 2D stuff, but iirc every texture2D is rendered through the GPU thing as some sort of flat 3D surface, so idk.


How can I develop in MonoGame without relying on .xnb files? I'm new to game development, and MonoGame seems like a beginner friendly framework, so thought I'd start with that. However, as I started reading tutorials on it, I noticed a common theme That at its current state, MonoGame needs XNA's content compiler since it doesn't have one of its own. The only problem I have with this is because I'm unable to install XNA (followed instructions on the web, even installed the Game Marketplace). I'm on Windows 8.1, by the way. Long story short, I gave up on trying to install XNA. However, I have played around a bit with MonoGame and found that you can use raw images (.png in my case) instead of those converted to .xnb. I haven't tried sound, so I don't know if it'll work. Or any other assets for the matter. My question is, is it possible to develop in MonoGame without using .xnb files? Or, is it possible to develop without XNA's content compiler? If yes, then how?


XNA tex2Dlod always returns transparent black I want to sample a texture in a vertex shader, so at first I just tried using float2 texcoords ... color tex2D(texture, texcoords) But apparently I cannot use tex2D in a vertex shader, and must use tex2Dlod. So then I changed the above code to color tex2Dlod(texture, float4(texcoords, 0, 0)) But now color is always float4(0, 0, 0, 0) (i.e. transparent black). Why is this, and how can I fix it? EDIT I know for a fact that the texture does not contain just transparent black pixels.


SpriteBatch, trying to reduce draw calls This my main draw call Matrix Camera transformation player camera .GetTransformation() Background AlphaBlend spritebatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, null, Camera transformation) background .Draw(spritebatch) spritebatch.End() Particles (of a player power, I want them behind him!) Additive spritebatch.Begin(SpriteSortMode.Deferred, BlendState.Additive, null, null, null, null, Camera transformation) player .DrawParticles(spritebatch) spritebatch.End() Player Alpha Blend spritebatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, null, Camera transformation) player .Draw(spritebatch) spritebatch.End() Hub Ui Not to be influenced by the camera, but always on top spriteBatch.Begin() UI.Draw(spritebatch) spriteBatch.End() Is there a way to reduce the number of calls here? If my particle system didn't need an additive drawing, I would have merged the first three calls, but I can't. Is there something I am missing about spritebatch ordering?


Fbx animation without bones or single skeleton SkinnedModel sample nicely shows how to import single root bone skeleton and run in XNA. My question are Is it possible to have animations played in XNA if there no bones are used in model (which can easily be done in 3dmax with auto key frames)? Is it possible to have multiple independent bones laying around, connected to independent meshes and animated, all played in XNA? Can SkinnedModelProcessor be downgraded to this level ?


How to modify Game1.cs out of an object it contains? Assuming I Have a List lt SomeClass gt myList in my Game1 class. It also contains an object of SomeOtherClass otherClass . How would I modify myList (Add Remove) out of the otherClass's logic? Or in other words how to get access to the Game1 instance in this situation?


Rotation pitch yaw reverse problems when picking a tile (2.5D) Set up 3D world, isometric sprite rendering (4 fixed angles). This transform matrix is used as camera transform Matrix.CreateRotationZ(Roll) Matrix.CreateRotationX(Pitch) Matrix.CreateTranslation(new Vector3( cameraPosition.X , cameraPosition.Y, cameraPosition.Z)) this matrix controls camera position Matrix.CreateScale(new Vector3( zoomScale)) scale representing zoom level. This one applies to the textures too Matrix.CreateScale(new Vector3( textureScale)) world scale to fit current texture pixel size. Matrix.CreateTranslation(new Vector3(( port.screenWidth 2) TileOffset, port.screenHeight 2, 0)) offset for having focus in center of screen instead of top left corner little offset so it will be a tile center Roll 45, Pitch 60. Result I've hoped to find a quick picking solution in the inverse matrix inverseTransform Matrix.CreateTranslation(new Vector3( ( port.screenWidth 2) TileOffset, port.screenHeight 2, 0)) Matrix.CreateScale(new Vector3(1 textureScale)) Matrix.CreateScale(new Vector3(1 zoomScale)) Matrix.CreateTranslation(new Vector3(cameraPosition.X, cameraPosition.Y, cameraPosition.Z)) Matrix.CreateRotationX( Pitch) Matrix.CreateRotationZ( Roll) It doesn't work as expected. If i remove rotation from matrix build, everything works. The interesting part is if i leave roll component only, everything works too. I've tried transposed matrices, inverted matrices, rotating on angle, FromPitchYawRoll matrix (inverted transposed angles). Every time roll works, pitch and yaw aren't. Pitch only yaw only can't be inverted too. It's probably something basic in the matrix math rotation principles, but i'm failing to grasp it. Any help would be appreciated. code removed, not relevant to the case Some gifs for better understanding. Current implementation do this If we switch the pitch off, inverse matrix work as intended (white dots mark real tiles grid. Graphical tiles aren't rotated, of course.) EDIT After some matrix calculations i've realised simple thing. Let's point the mouse on the tile (0,2). If i dump all transformations but pitch by several degrees, then tile (0,2) will be drawed somewhere on (0, 1.25). But if i'll apply inverted (or transposed, or "rotate by value") matrix to the mouse position (0,2), i'll get same (0, 1.25), which means that the mouse is pointing at (0,1) tile. While it should point at (0, 3). And i don't know how to invert this correctly. I've also discovered this. But, as you can see in the first answer, knight666 is using scale instead of pitch rotation.


How to move a line of sprites in a sine wave? So, I'm spawning a horizontal line of enemies that I would like to have move in a nice wave. Currently I tried Enemy.position.X Enemy.velocity.X Enemy.position.Y (float)Math.Cos(Enemy.position.X 200) 5 This...kind of works. But the wave is not a true wave. The top and bottom of one pass are not the same (e.g. 5 for the top, and 5 for the bottom (I don't mean literal points, I just meant that it's not symmetrical)). Is there a better way to do this? I would like the whole line to move in a wave, so it looks fluid. By that, I mean that it should look like each enemy is "following" the one in front of it. The code I posted does have this fluidity to it, but like I said, it's not a perfect wave. Any ideas? Thanks in advance.


How to set multiple times, in a single spritebatch, the same pixel shader parameter I make a test with Effect class in XNA and I want to set multiple times the same parameters (MyParameter in below code). My code is ... In Engine class Effect ShaderEffect GameEngine.Instance.Content.Load lt Effect gt ( "shaders test") spriteBatch.Begin( SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointWrap, DepthStencilState.Default, RasterizerState.CullNone, ShaderEffect) ... in drawable class foreach( big loop) ShaderEffect.Parameters "MyParameter" .SetValue( random vector4) spriteBatch.Draw( SpriteSheet, ScreenRect, sprite to draw.Rectangle, color, rotation, Scene.getInstance().Camera.Position, sprite to draw.SpriteEffect, layer ) ... In Engine class spriteBatch.End() ... But on my screen it look like the Parameter "MyParameter" is not overwrite. So can I overwrite it and If yes do you know how ? Thanks


Setting up 3d Collision for Primitive shapes Im having some trouble understanding how to set up collision detection between my first person camera and my primitive shapes which are made using the vertex buffer. Do i give my camera a boundingBox and all my objects a boundingbox then add them to a list and check the list for collsions or is there a better more understanding way to do this. My game is literally a maze game so all i really need is my camera to accept collisions against the primitive objects. Thanks in advance.


XNA Skinning Sample exporting from Blender recognize only first animation clip (and sorry for my English) I'm using animation components from XNA Skinning Sample. It works great but when I export a model from Blender, it does not recognize any other animation clips than the first one. So I have three animation clips, but XNA recognize only one. Also, when I looked up on Xml file of the model in Debug Content obj directory, there is only one animation clip, but when I check code directly from .fbx file, it seems to be alright. Link to my model files https skydrive.live.com redir?resid 8480AF53198F0CF3!139 BIG Thanks in forward!


Colors set in Blender not displayed in XNA I'm trying to create a colored 3D model for my XNA game in Blender. I don't want to use textures I need only solid colors. Here's the model, as seen in Blender After exporting to FBX and opening in Visual Studio 2012 (some kind of built in viewer I guess), the lightning isn't perfect but the colors are preserved But something's wrong when I try to display it using XNA Here's my code for displaying objects protected void DrawModel(GameObject obj, bool semitransparent false, float angle 0.0f) var transforms new Matrix obj.Model.Bones.Count obj.Model.CopyAbsoluteBoneTransformsTo(transforms) foreach(var mesh in obj.Model.Meshes) foreach(BasicEffect effect in mesh.Effects) effect.EnableDefaultLighting() Game.GraphicsDevice.BlendState semitransparent ? BlendState.AlphaBlend BlendState.Opaque effect.Alpha semitransparent ? 0.5f 1.0f if(obj is Player false) effect.DiffuseColor obj.IsHighlighted ? new Vector3(1.0f, 0.0f, 0.0f) new Vector3(1.0f, 1.0f, 1.0f) effect.World transforms mesh.ParentBone.Index Matrix.CreateRotationY(angle) obj.TransformMatrix effect.View ViewMatrix effect.Projection ProjectionMatrix mesh.Draw() Why is the whole model white instead of colored? I set colors of the parts by creating a new material and setting its diffuse component to the color I want. All other settings have their default values. I thought that it's a matter of setting effect.VertexColorEnabled to true, but that gives me an InvalidOperationException saying The current vertex declaration does not include all the elements required by the current vertex shader. Color0 is missing.. Do I need some kind of shader that will understand Blender's vertex properties and will display the model correctly?


How to fill a rectangle with tilable texture in XNA? So, question in the title. I don't know how to create infinite seamless background.


How do I use render targets in XNA? I'm trying to render text (or whatever) off screen. But I have a strange issue where the render target size matches the window size and not the render targets size. Yes, it is a contradiction! Here's the render target And here's the code, chopped up and put together to demonstrate what's happening in one place UserInterface.SpriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.None, RasterizerState.CullNone) RenderTarget2D rt new RenderTarget2D(UserInterface.GraphicsDevice, 200, 200) UserInterface.GraphicsDevice.SetRenderTarget(rt) UserInterface.GraphicsDevice.Clear(Color.Blue) Rectangle rect new Rectangle(0, 0, 200, 200) UserInterface.SpriteBatch.Draw(pixel, rect, Color.White) renderTarget.GraphicsDevice.SetRenderTarget(null) UserInterface.SpriteBatch.End() if (frame 0) rt.SaveAsJpeg(File.OpenWrite("renderTarget.jpg"), rt.Width, rt.Height) The render target is created at 200x200, I then set the render target on the graphics device. I clear it to blue and draw a pixel at 200x200 (in white). Lastly, I save off the render target. But why does the sprite batch render the pixel in proportion to the window (just take my word that it is rectSize WindowSize RTSize) rather than filling the render target which I believe it should do in this case?


How can I load 24 bit audio as SoundEffect? When I try to load .wav file I get an error Audio file .wav contains 24 bit audio. Only 8 bit and 16 bit audio data is supported. Here is my code SoundEffect menuSelectionChange content.Load lt SoundEffect gt ("Sound Menu Selection Click") SoundEffectInstance menuSelectionChangeInstance menuSelectionChange.CreateInstance() Even if I delete this code I'm still getting this error.


Timer for pop up text in XNA I am making an xna game which contains turn based RPG battle elements. Any good game that features turn based battle has to have a good feedback to the user. For example, When my guy attacks, there should be a text popup that says something like "HERO DOES 15 DMG!". And this text should disappear several seconds after. I am currently able to put text on the screen via standard spritefont drawing. However, in order to make it disappear I am currently using bools and a timer. I have been doing research on timing related stuff but I seem to be very bad at it. Using some of the suggestions I have received, I have made a messagesystem class. But I am still confused about the implementation. Here is the new code public class MessageSystem public static readonly MessageSystem Instance new MessageSystem() public float timenow struct Message public SpriteFont Font public string Data public Vector2 Position public float Duration public bool isActive get set List lt Message gt Messages new List lt Message gt () public MessageSystem() public void Show(string data, Vector2 pos, SpriteFont font, float duration) Messages.Add(new Message() Data data, Font font, Position pos, Duration duration ) public void Update(GameTime gameTime) timenow (float)gameTime.ElapsedGameTime.TotalSeconds for (int i 0 i lt Messages.Count ) if (Messages i .Duration lt timenow) Messages.RemoveAt(i) continue i public void Draw(SpriteBatch batch) foreach (Message msg in Messages) batch.DrawString(msg.Font, msg.Data, msg.Position, Color.Lime) Here is the implementation part if (p1atktimer gt 10) AttackMsg.Show(playerBattler.Name " attacks furiously!", battlemsgs, battlefont, 2.0f) DealDmgFromLeft(gameTime) p1atktimer 0 timenow 0 In my update method I just have Attackmsg.Update(gameTime) And similarly, in my Draw method I have Attackmsg.Draw(spriteBatch) So, it goes away when it is supposed to, but it does not appear again when the p1atktimer condition becomes true again. I guess i have to surround the attackmsg.Draw(spriteBatch) command with conditionals instead of the show? But this brings me back to my previous question Do I have to make bools for everytime I want to show this kind of text. Let's continue with this example, I am going to make a bool atkmsgshowing false. And make it true when someone's attackguage reaches 10. Because, if I do not do this, the msg works only once. So then, the attacker attacks, and I will make the bool true. When the attack ends, atkmsgshowing will go back to false. Doesn't this defeat the purpose of making a MessageSystem class?


XNA 4.0 Normal mapping shader strange texture artifacts I recently started using custom shader. Shader can do diffuse and specular lighting and normal mapping. But normal mapping is causing really ugly artifacts (some sort of pixeling noise) for textures in greater distance. It looks like this This is HLSL code Matrix float4x4 World World float4x4 View View float4x4 Projection Projection Textury texture2D ColorMap sampler2D ColorMapSampler sampler state Texture lt ColorMap gt MinFilter Anisotropic MagFilter Linear MipFilter Linear MaxAnisotropy 16 texture2D NormalMap sampler2D NormalMapSampler sampler state Texture lt NormalMap gt MinFilter Anisotropic MagFilter Linear MipFilter Linear MaxAnisotropy 16 Light float4 AmbientColor Color float AmbientIntensity float3 DiffuseDirection LightPosition float4 DiffuseColor Color float DiffuseIntensity float4 SpecularColor Color float3 CameraPosition CameraPosition float Shininess The input for the VertexShader struct VertexShaderInput float4 Position POSITION0 float2 TexCoord TEXCOORD0 float3 Normal NORMAL0 float3 Binormal BINORMAL0 float3 Tangent TANGENT0 The output from the vertex shader, used for later processing struct VertexShaderOutput float4 Position POSITION0 float2 TexCoord TEXCOORD0 float3 View TEXCOORD1 float3x3 WorldToTangentSpace TEXCOORD2 The VertexShader. VertexShaderOutput VertexShaderFunction(VertexShaderInput input, float3 Normal NORMAL) VertexShaderOutput output float4 worldPosition mul(input.Position, World) float4 viewPosition mul(worldPosition, View) output.Position mul(viewPosition, Projection) output.TexCoord input.TexCoord output.WorldToTangentSpace 0 mul(normalize(input.Tangent), World) output.WorldToTangentSpace 1 mul(normalize(input.Binormal), World) output.WorldToTangentSpace 2 mul(normalize(input.Normal), World) output.View normalize(float4(CameraPosition,1.0) worldPosition) return output The Pixel Shader float4 PixelShaderFunction(VertexShaderOutput input) COLOR0 float4 color tex2D(ColorMapSampler, input.TexCoord) float3 normalMap 2.0 (tex2D(NormalMapSampler, input.TexCoord)) 1.0 normalMap normalize(mul(normalMap, input.WorldToTangentSpace)) float4 normal float4(normalMap,1.0) float4 diffuse saturate(dot( DiffuseDirection,normal)) float4 reflect normalize(2 diffuse normal float4(DiffuseDirection,1.0)) float4 specular pow(saturate(dot(reflect,input.View)), Shininess) return color AmbientColor AmbientIntensity color DiffuseIntensity DiffuseColor diffuse color SpecularColor specular Techniques technique Lighting pass Pass1 VertexShader compile vs 2 0 VertexShaderFunction() PixelShader compile ps 2 0 PixelShaderFunction() Any advice? Thanks!


How do I organize my game into multiple classes in C ? I've made two simple 2D games while following tutorials for the XNA libraries, and I wanted to make something myself, with only the knowledge I gained from these tutorials. This will be my first serious attempt at game development, as well as my first C XNA project. I migrated from Java a week ago. Now, both of the tutorials I've followed made the whole game using only one class. And while it's possible, it isn't organized enough for me, and I want most of the functions to be organized in separate classes. So, I started with Input so I can have an easy way of exiting the game during testing right away. Here's the important bits, I think From my Game1.cs protected override void Update(GameTime gameTime) Input input new Input() input.PollInput() TODO Add your update logic here base.Update(gameTime) From my Input.cs namespace MyFirst2DGame class Input Game1 game new Game1() public void PollInput() if (GamePad.GetState(PlayerIndex.One).Buttons.Back ButtonState.Pressed) game.Exit() However, when I run the project, the Back button on the XBox 360 controller does nothing. My question, is am I missing something? I have no idea how to do anything with multiple classes, as all of my Java projects were quite small and had need for only one class.


How to properly handle collision in a component based game? Trying to wrap my head around the ways to properly handle collision in a game designed around components. I see many examples have some sort of PhysicsComponent that gets added to the entity's list of components but the actual implementation is confusing me. For this to work, the PhysicsComponent would need access to the world around it. This doesn't make intuitive sense to me. Shouldn't a component be unaware of not only its container (the entity), but its container's container (the world)? To me, it sounds like the level or scene should maintain a list of these entities and every game update, loop through the entities to determine which collide. My question is firstly, whether or not this is good design, and secondly, how to determine which entities can collide. I suppose solid entities could implement an empty IRigidBody interface so the level could determine which entities in the list support collision. But is this breaking the component design? Instead, should they contain an empty RigidBody component? This may actually be better because it may not always be empty and this approach is more future proof. The only problem with this is the complexity. The scene would have to loop through not only every entity, but also every entity's components to determine if it had this RigidBody component. Thirdly, when they do collide both entities should be informed somehow and I am unsure on how to accomplish this either. Let's say that both entities contained a HealthComponent and when they collided both their healths would be decreased by some arbitrary value, 5. I suppose it would be the scene's responsibility to handle this when it detects a collision between two entities? But then is the scene responsible for too much? I could see this possibly getting out of hand and becoming unwieldy when the scene is responsible for many things entities should not (?) have access to. Edit Question updated with more details.


3D Procedural Planet Generation I was looking for some inspration for my Voxel based game I am writting and came across this http www.youtube.com watch?v rL8zDgTlXso. I would like to know how to go about (or preferably source examples) of how I would do that, in real time, and infinitley. In addition to that I was wondering how I would do this with a voxel based terrain? A procedural planet generator in 3D which constructs voxel data, my voxels are of the same size of thoose in minecraft. Any ideas? Edit I ported the simplex noise function i grok suggested written in C Python to C , I sure hope it works ) http pastebin.com TZSQwnye Edit 2 float noise(float x, float y, float z, float persistance, float amplitude, float frequency, float octaves) float total 0 for (int i 0 i lt octaves i ) frequency frequency i or frequency 2 ? amplitude amplitude i total total SimplexNoise.raw noise 3d(x frequency, y frequency, z frequency) amplitude return total


Zune same features as WP7? (gesture, accelerometer) We don't have zune HD in Canada (yet) just wondering if it has the same programmable features as WP7? Like gestures and accelerometer. Basically if I am just making a game, with screen controls (thumbsticks on the screen) is this an easy port to zune? Thanks!


XNA 4 Monogame 3d tunnel collision I am trying to collide an aircraft with a FBX tunnel model. I don't know how to create multiple bounding boxes for a tunnel. The tunnel is contains a single mesh. I tried using the triangle picking sample here http xbox.create.msdn.com en US education catalog sample picking triangle I also created a bounding sphere around the tunnel to be able to detect if the aircraft is inside the tunnel. If the ship is inside the tunnel then I check the triangle amp ray intersection. I also detect the intersection. I tried changing the rotation and position of the ship when intersection occurred but although I can detect the intersection ship passes through the tunnel surface mostly and my rotation doesn't work well. I also tried to calculate ray amp plane (here it is triangle) reflection as below if (intersection lt 0.4f) Plane pickedTriangle new Plane(vertex1, vertex2, vertex3) Vector3 reflectionVector Vector3.Reflect(direction, pickedTriangle.Normal) newPosition modelPosition direction gameSpeed reflectionVector newDirection reflectionVector tIntersected true As I see newPosition isn't calculated correctly. My question is how can I calculate a new position after a ray amp plane intersection. I think this causes the ship sometimes pass the tunnel surface sometimes. If there is a better way to detect and calculate tunnel collision I'll appreciate it. Thanks


How calculate a new node after cutting a node into an octree I'm working on a small XNA game, voxel based like minecraft. I've recently faced a problem in how to delete a node (cube) from an octree and re calculate the new octree afterward. I have already tried searching for implementations of the algorithm on the net, but without success. This is the function I tried RemoveCubeFromNode region RemoveCubeFromNode Remove a node from an Octree private BoundingBox RemoveCubeFromNode(BoundingBox cubeToDelete, BoundingBox cubeParent ) ...... split the cube from parent return the two new BoundingBoxes endregion Here are the pictures that represent what should be my functionality Knowing that my function should always return 2 new cubes (boundingBox) or 1 only. In red is the cube to remove In brown and blue are the two new cubes calculated A thousand thanks in advance to whoever can help me... this algorithm is driving me crazy, and I can not stop thinking that someone else must have had this problem too. The way about how i calculate my octree from my world First I initialize an integer array with 3 dimensions. Where each integer value corresponds to a structure id. 0 no structure (empty) 1 land 2 water etc ... public void generateMatriceWorld() int matrice null int widthMap 1024 int lengthMap 1024 int heightMap 64 matrice new int widthMap for (int i 0 i lt widthMap i ) matrice i new int lengthMap for (int j 0 j lt lengthMap j ) matrice i j new int heightMap randoom put value Inside my world After that i use the method where I divide my world 8 blocks by 8 blocks if more than one floor, and 4 if one floor. And this until the blocks structure curently cutted get the same structure .


ResourceContentManager with folders I am attempting to do something like the following http blogs.msdn.com b shawnhar archive 2007 06 12 embedding content as resources.aspx (Access the content via a DLL) However, I need to maintain the folder structure of the fonts and images. I have attempted to add the folders to the resources file, but it doesn't add the folder if I drop it in the resources file in VS. I am thinking I might need to embed the content as just a regular folder, and each file will need its property to be set to embedded resource, but I need to use it in another assembly. I looked at http zacharysnow.net 2010 07 03 xna load texture2d from embedded resource but I think I can only do that with textures. I need to do it with fonts as well. I looked at https stackoverflow.com questions 859699 how to add resources in separate folders and that doesn't seem to help me much. Whats the best way I can embed my resources in another assembly, while maintaining my content loading strings?


Should I bother merging faces in my 3D block based game? Okay, so I have a bunch of cubes in a 3d world. I already implemented face culling, so that when a cube is next to another cube, their touching faces won't be drawn, or even sent to the buffer. However, a while back when I was still researching how to make a 3d block based game, I came across a stack overflow question where the asker posted an image of their cubes, which had not only been culled but they had also merged the faces of adjacent cubes into larger rectangular faces. Like this My question is, should I do this? Will the drawing time be saved enough to justify the longer update time? And if so, I'm not even sure if it would work some of the time. The cubes aren't textured, they're coloured, so I'm not entirely sure if it would work with multiple colours of cubes.


XNA 4.0 Using premade .xnb font files Basically, for our college project, we need to use a font in xna. The only problem is that we are not allowed to install it due to admin rights. Is it possible to use and load the .xnb file that gets created as the font. Using spritefont gives errors as it searches for the font in windows. (The .xnb file will be created on someones personal machine beforehand.)


Collisions between moving ball and polygons I know this is a very typical problem and that there area a lot of similar questions, but I have been looking for a while and I have not found anything that fits what I want. I am developing a 2D game in which I need to perform collisions between a ball and simple polygons. The polygons are defined as an array of vertices. I have implemented the collisions with the bounding boxes of the polygons (that was easy) and I need to refine that collision in the cases where the ball collides with the bounding box. The ball can move quite fast and the polygons are not too big so I need to perform continuous collisions. I am looking for a method that allows me to detect if the ball collides with a polygon and, at the same time, calculate the new direction for the ball after bouncing in the polygon. (I am using XNA, in case that helps)


How i can do colisions with irregular hitboxes? I'm developing my new platform engine and i don't know how to program collisions with slopes I'm using hitboxes. For the collisions of rectangles i use this if (player.rec(Position, level.scale).Intersects(t.rec(level.scale))) but this doesn't work for sloped collisions or triangular hitboxes. How can I do this?


Why are .xnb files used rather than source files? XNA and Monogame are built using a content pipeline, which takes source files (images, sound effects, 3D models, etc.) and converts them to proprietary .xnb files. What's the benefit of doing this as opposed to simply loading source files directly? To be clear, I'm not asking how to use the content pipeline. Just why .xnb files are used in the first place.


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


Monogame XNA How do you resize a Texture2D and then scale it? Problem It seems like the Draw() call allows us to use either Destination Rectangle for resizing (5of8) or Scale (6of8 7of8) but not both. Purpose I would like to resize a button from 567x634 to 400x480 and then using scale to further reduce it by 0.8 to 320x400.


2D Tile based Collision Detection I've been planning an indie game project for a while now. I'll summarise it for you so I can get right to the question. It's done entirely using the latest version of XNA through Visual Studio. Hoping to put it on 360 and PC, but am only really looking for a PC oriented solution at this stage. It's a 2D side scrolling shooter (think Metroidvania style, or even Terraria). It will eventually include an in game map editor with maps being tile based (16x16). There will be upwards and downwards scrolling. I'm hoping to implement tile layers in the dev map editor (reason for a dev map editor is it's going to be heavily leaning towards a content focus, so there will be a lot of maps). Physical tiles will be very simple with only two major types. Block tiles, which are just a solid tile, and angled tiles, which are tiles with an incline that characters can walk on. I'm strongly considering abandoning angled tiles entirely, but not sure yet. The character NPC movement will be simple. Moving side to side, jumping, falling, flying (with appropriate items situations), teleporting. All very static, no dynamic physics necessary. Only basic gravity. When a character steps off the edge of a tile, it falls. When it jumps and a tile is above it, it stops short and falls back down. When it reaches a protruding tile wall, it can't move further unless it jumps over or flies. All the basic stuff. Projectiles can be affected by gravity as well, and some situations may arise where a projectile may be manipulated mid flight, but nothing requiring heavy physics. Some projectiles will move characters as well (think a simple "pushing" mechanic). So here's the question I'm at the stage where I'm starting to work on movement and collision detection but I just can't set myself on a way to go about them. I need ways to determine when character, tiles, and projectiles collide. Given what I've said about the style I'm going for and the tile based system I'm using, can I get some recommendations links to some tried and true collision detection methods others have used in similar situations, and maybe an example of a game using a similar approach? What I need more than anything else is inspiration. And just a quick note, I have several years of experience as a programmer, so I'm not a total newbie )


XNA Why is Texture.GetData one dimensional? This is question has been really killing me. In XNA when you want to convert an image to color data using Texture.GetData, it only lets you make it a one dimensional array instead of a 2D one. This makes it much more difficult to work with. Is there a specific reason it's like that?


Keep 3d model facing the camera at all angles I'm trying to keep a 3d plane facing the camera at all angles but while i have some success with this Vector3 gunToCam cam.cameraPosition getWorld.Translation Vector3 beamRight Vector3.Cross(torpDirection, gunToCam) beamRight.Normalize() Vector3 beamUp Vector3.Cross(beamRight, torpDirection) shipeffect.beamWorld Matrix.Identity shipeffect.beamWorld.Forward (torpDirection) 1f shipeffect.beamWorld.Right beamRight shipeffect.beamWorld.Up beamUp shipeffect.beamWorld.Translation shipeffect.beamPosition Note Logic not wrote by me i just found this rather useful It seems to only face the camera at certain angles. For example if i place the camera behind the plane you can see it that only Roll's around the axis like this http i.imgur.com FOKLx.png (imagine if you are looking from behind where you have fired from. Any idea what to what the problem is (angles are not my specialty) shipeffect is an object that holds this class variables public Texture2D altBeam public Model beam public Matrix beamWorld public Matrix gunTransforms public Vector3 beamPosition


How to generate Spritefonts for monogame I just want to render some text to the screen using monogame 3.0 MS Visual Studio 2010 C Express In XNA, you were able to add fonts to the content pipeline quite easily. But this doesn't seem to be the case in monogame. Loading TTF Files using Content lt SpriteFont gt .Load() doesn't work. Is there any way to generate or download .spritefont files or .xnb files containing the font data (without resorting to install XNA)?


Display crosshair that is diplaying where the ship is aiming at I am creating a 3D asteroids game. I got the bullets, asteroids, and ship all done. They work perfectly. Now I want a crosshair to display where the ship is pointing at. The crosshair will be a 2D sprite.


XNA move from start position to target position exactly in 3D If I have a list of positions that map out a path a character should follow. What would be the best way to move at a constant speed to each position making sure the character lands exactly at each position before moving onto the next? For example the character is at position A, we then queue up position B and position C. The character cannot move towards position C until it reaches position B exactly. It would be great if the solution worked at slower frame rates update speeds as well.


Where does the Game class come from in the DrawableGameComponent constructor? I'm making a project to Windows Phone using Silverlight XNA, but I don't know how I can use the DrawableGameComponent because the constructor requires a Game class, it looks like this Planet.cs class Planet DrawableGameComponent public Planet(Game game) base(game) but in my first page of Silverlight and XNA project not is a Game class it's this GamePage.xaml.cs public partial class GamePage PhoneApplicationPage ... Where do I find the Game class to pass into the DrawableGameComponent constructor?


2D Tile Game Smooth Biome Terrain Transitions While working on my 2D tile based game, I encountered a problem. I use Perlin Noise to generate the terrain. Some biomes (Desert, Forest, etc) have different flatness values depending on terrain, which causes the end start of a new biome to have a big cliff because the terrain is different. When 2 biomes have the same flatness, they are fine, but if they are different, this can happen. Is there any way to keep this from happening? Example (In programmer art)


Sprite Animation Using Multiple Images (XNA C ) all. Right now I am currently working on a game with my Australian buddy and I just am having such a difficult time with the spriting process. As the programmer of our game, it is my responsibility to get the sprites he models drawn and animated onscreen. However, the sprites he's drawing are huge images and the animation sequences are always at least 20 images wide, which means they're too big for the FileOpen method to read... Which brings me to my question Is there a way to use a directory as the animation sequence? Like instead of stringing all the images together in a chain and animating the sequence, can I make an animation from a collection of the images in a folder? For this example, use Animation.png to represent the chain of images version and Image1, 2, and 3.png for individual images in a directory. Thanks in advance!


How are components properly instantiated and used in XNA 4.0? I am creating a simple input component to hold on to actions and key states, and a short history of the last ten or so states. The idea is that everything that is interested in input will ask this component for the latest input, and I am wondering where I should create it. I am also wondering how I should create components that are specific to my game objects I envision them as variables, but then how do their Update Draw methods get called? What I'm trying to ask is, what are the best practices for adding components to the proper collections? Right now I've added my input component in the main Game class that XNA creates when everything is first initialized, saying something along the lines of this.Components.Add(new InputComponent(this)), which looks a little odd to me, and I'd still want to hang onto that reference so I can ask it things. An answer to my input component's dilemma is great, but also I'm guessing there is a right way to do this in general in XNA.


Absorbtion 2d image effect I want to create a specyfic 2d image effect. It consists in modifying a sprite so it looks like it is being zoomed to a point or "absorbed" by that point. I'm not really sure what is the technical name of this effect so I cannot explain it correctly. Here you can see a video of what I'm talking about, it is the effect when the character absorbs the three glyphs. http www.youtube.com watch?v PIo GddsMcU amp t 4m45s What is the name of this effect? How can I implement it with XNA for 2D textures sprites?


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?


Rotate 3D Model from a custom position I have a 3D Model like above in which i want to rotate it from a given location(pointed in red) but I can only rotate it from the middle. How can I rotate it from a custom point. Edit I successfully able to rotate the model from the below position by getting the radius of the model and applying it to the world matrix Vector3 point new Vector3( radius, 0, 0) world Matrix.CreateTranslation( radius, 0, 0) But now I cannot change the position of the object and it always centered in middle of the screen. I think that's because i applied the above code. How can I place it anywhere I want?


SpriteBatch.Draw() rectangle is different from destinationRectangle passed in When I ask SpriteBatch to draw a rectangle as within the following method public static void DrawSolidRectangle(Rectangle rectangle, Color color) the output from this is shown in the screenshot System.Console.WriteLine(rectangle.ToString()) spriteBatch.Draw(pixel, rectangle, color) I am getting different sized rectangles to the rectangles I am providing. This is an issue I am having after resizing the window. As you can see in the screenshots, the difference in width of the two rectangles is only 2 pixels and there is an offset of 1 pixel, while the two gray rectangular draw results clearly have greater than a 3 pixel difference in width. screen shot of issue http users.tpg.com.au gavinw77 SpriteBatchIssue.jpg Does anyone know what's going on ? Is this a known issue with SpriteBatch or the BackBuffer after resizing or what ?


Detecting "Any Button Press" I'm trying to allow the player to press any button to continue from the main page. I was able to do this by making a List of Buttons and looping through these and checking for one of them being down however, I feel like this code is kind of ugly and wonder if there's a simpler way to do it that I'm just not thinking of? Here's my what my code looks like now if (GamePad.GetState(PlayerIndex.One).IsConnected) var buttonList new List lt Buttons gt () Buttons.A , Buttons.B , Buttons.Y , Buttons.X , Buttons.Start , Buttons.Back , Buttons.RightShoulder , Buttons.LeftShoulder , Buttons.RightTrigger , Buttons.LeftTrigger foreach (var button in buttonList) if (GamePad.GetState(PlayerIndex.One).IsButtonDown(button)) ExitMainMenu true


Texture Mapping in Blender XNA I have a simple Blender Model (just a few faces). I want to add 2 Textures. (a special face should get Texture 1, the other faces Texture 2). This model I want to use in XNA. The first Texture should be replaceable at Runtime by Code (the new image is generated based on user input). So how do I best solve this Using UV Maps or Normal based Maps in Blender? How can I access the Blender UV Mapping in XNA? Or do I completely perform the Texturing in XNA (using Code or shaders)? And how (I m new to this)?


2D Physics Engine to Handle Shapes Composed of Multiple Densities XNA The game I'm working on involves shapes that might be composed of multiple materials in a variety of ways. Let's just take for example a wooden rod with and sizable tip of iron or say a block composed of a couple triangles of stone and aluminum and small nugget of gold. The shapes and compositions will change from time to time, so I was wondering what engine I should use and how I might implement this feature? I've looked at Farseer 3, but I'm still trying to decipher the library by reading the source and the samples and wasn't sure if I was barking up the wrong tree. Thanks!


Issues with 2D Body Limb system In my game I have programmed Body and Limb classes. The Body is guaranteed to have an origin in the center of its sprite. The Body class has a List of children Limbs, each with their own offset. Every Limb has a Master value which references the parent Body, but it also has a Parent value which references the Limb it is a child of. However, Limbs do not have to have a parent, they can directly connect to the Body. The Master, Parent, and Children values of the Limb class Body containing all limbs this limb is connected to and others. public Body Master get set Parent limb, if null then limb directly connected to the body. public Limb Parent get set Children limbs public List lt Limb gt Children get set The Limb methods have if statements to handle these situations. In relation to the offsets and rotations of the Limbs around the Body (using transformation matrices) things seem to work fine. Now, the problem I'm having is when a Limb is attached to another Limb. The child Limb draws and behaves as if it is rotating around the Body instead of its parent Limb, and the parent Limb itself vanishes. Limbs without Children that are directly connected to the Master Body have no issues. Because of this sort of recursive hierarchy I believe the problem has to do with reference types but I may be mistaken. Here is some additional code Demonstration Here is the worldPosition() method which is used to acquire the Limb's position in world space. I suspect it may be the culprit. The Master.Position is already in world space public Vector2 worldPosition() if (Parent ! null) return (LocalPosition Parent.worldPosition()) else return (LocalPosition Master.Position) Finally here is the Update() method of the Limb class http pastebin.com 5L5v5p6x EDIT Upon further analysis it appears that any changes I make to either Limb seem to affect the other Limb in one way or another even though they are both quite clearly different instances. Here is the code to make the initial Body and first Limb b new Body() Sprite FileFactory.Textures "shoulders" , Position new Vector2(this.Position.X, this.Position.Y), Limb l new Limb() Sprite FileFactory.Textures "left arm" , Master b, Offset new Vector2(2, 13), Origin new Vector2(0, Sprite.Height 2), RotationalDifference (float)(0.2 Math.PI), RotateSpeed 0.15f b.Children.Add(l) b.Initialize() And the code to add the child Limb to the first (Parent) Limb Children.Add( new Limb() Sprite FileFactory.Textures "right arm" , Master this.Master, Parent this, Offset new Vector2(27, 0), Origin new Vector2(0, Sprite.Height 2), RotationalDifference (float)(0.2 Math.PI), RotateSpeed 0.15f )


Information about rendering, batches, the graphical card, performance etc. XNA? I know the title is a bit vague but it's hard to describe what I'm really looking for, but here goes. When it comes to CPU rendering, performance is mostly easy to estimate and straightforward, but when it comes to the GPU due to my lack of technical background information, I'm clueless. I'm using XNA so it'd be nice if theory could be related to that. So what I actually wanna know is, what happens when and where (CPU GPU) when you do specific draw actions? What is a batch? What influence do effects, projections etc have? Is data persisted on the graphics card or is it transferred over every step? When there's talk about bandwidth, are you talking about a graphics card internal bandwidth, or the pipeline from CPU to GPU? Note I'm not actually looking for information on how the drawing process happens, that's the GPU's business, I'm interested on all the overhead that precedes that. I'd like to understand what's going on when I do action X, to adapt my architectures and practices to that. Any articles (possibly with code examples), information, links, tutorials that give more insight in how to write better games are very much appreciated. Thanks )


Going fullscreen without stretching in an XNA game I've got a 2D game that I'm working on that is in a single aspect ratio. When I switch it to fullscreen mode on my widescreen monitor it stretches. I tried using two viewports to give a black background to where the game shouldn't stretch to, but that left the game in the same size as before. I couldn't get it to fill the viewport that was supposed to hold the whole game. How can I get it to go fullscreen without stretching and without me needing to modify every position and draw statement in the game?


Microsoft XNA code sample wont work with blender model I downloaded this code sample and integrated it into my game http xbox.create.msdn.com en US education catalog sample mesh instancing It works with the model that they supplied, but throws and exception whenever I use one of my models. The current vertex declaration does not include all the elements required by the current vertex shader. TextureCoordinate0 is missing. I tried pluging my model into their original source code and same thing. My model is an fbx from blender and has a texture. This is the function that throws the error GraphicsDevice.DrawInstancedPrimitives( PrimitiveType.TriangleList, 0, 0, meshPart.NumVertices, meshPart.StartIndex, meshPart.PrimitiveCount, instances.Length )


Why is 2D light ray collision result getting inverted at specyfic angle recently i've been working on 2D lighting for my game. I've created new little project, and I've encoutered a problem. The collision between light ray and the object is fine at angles 316 360 and 0 136 degrees. On the others, light gets inverted (it's gone form the source to the object, and it's present on the 'dark side'. I know the code isn't efficient, it's just my concept project, I would like you just to help me understand what is going on in here. Here's a function that checks for collision, for every single point in a light ray. public Vector2 Intersects(Rectangle rectangle,SpriteBatch s) Point p0 new Point((int)startPos.X, (int)startPos.Y) Point p1 new Point((int)endPos.X, (int)endPos.Y) foreach (Point testPoint in BresenhamLine(p0, p1)) if (rectangle.Contains(testPoint)) s.Draw(this.texture, new Rectangle(testPoint.X, testPoint.Y, 3, 3), Color.Black) return new Vector2((float)testPoint.X, (float)testPoint.Y) else final testPoint s.Draw(this.texture, new Rectangle(testPoint.X, testPoint.Y, 3, 3), Color.Black) s.Draw(this.texture, new Rectangle(final.X, final.Y, 2, 2), Color.Black) return Vector2.Zero Swap the values of A and B private void Swap lt T gt (ref T a, ref T b) T c a a b b c Returns the list of points from p0 to p1 private List lt Point gt BresenhamLine(Point p0, Point p1) return BresenhamLine(p0.X, p0.Y, p1.X, p1.Y) Returns the list of points from (x0, y0) to (x1, y1) private List lt Point gt BresenhamLine(int x0, int y0, int x1, int y1) List lt Point gt result new List lt Point gt () bool steep Math.Abs(y1 y0) gt Math.Abs(x1 x0) if (steep) Swap(ref x0, ref y0) Swap(ref x1, ref y1) if (x0 gt x1) Swap(ref x0, ref x1) Swap(ref y0, ref y1) int deltax x1 x0 int deltay Math.Abs(y1 y0) int error 0 int ystep int y y0 if (y0 lt y1) ystep 1 else ystep 1 for (int x x0 x lt x1 x ) if (steep) result.Add(new Point(y, x)) else result.Add(new Point(x, y)) error deltay if (2 error gt deltax) y ystep error deltax return result


How to convert Texture2DContent to Texture2D in custom ContentTypeReader I'm trying to implement a custom ContentPipeline extension that writes a Surface object with a Texture2D member. My input file is an xml with fields for all of my Surfaces and their members. In the xml, my Surface's Texture2D is represented by a path to an image file. In my ContentProcessor, I want to load the Texture2D from the image file path, then write that texture data straight into my object's xnb with the rest of a Surface's members. Right now, I've got the ContentTypeWriter writing a different ("CompiledSurface") object with a Texture2DContent member. The Texture2DContent is created in the ContentProcessor using BuildAndLoadAsset(string path). My importer, processor, and writer all seem to be doing their jobs. But in my ContentTypeReader, I can't figure out how to convert the Texture2DContent back to a Texture2D in order to create my runtime object. Any help is much appreciated. class Surface protected Rectangle bounding box protected Texture2D texture ... class CompiledSurface public Texture2DContent texture public int x public int y ...


Outlining external edges on a complex shape made of cubes? A gallery of my problem can be found here. I had to do it this way as it won't let me post more than 2 links due to my reputation. I'm trying to use 3D cubes to generate an isometric cube world. I got that working great and I merge only the visible vertices indices into a buffer and draw from that. Only problem is, as with any isometric game, it becomes difficult to differentiate between heights. For example in the first image this archways top merges with the cubes below. I ended up finding this shader and got it working by using it against a rendered normal map (second image) of the cubes. You may be able to guess my problem from that image. The final result looks like the third image. The back edges are not draw with an outline, which are the most important. Which based on the normal map also means that diagonals also have the same problem on their sides (fourth image). Is there any solution I can do for this? Either in the shader itself or perhaps when calculating the normals? I almost need to add something to the normal to distinguish their depth height so faces on similar planes don't merge on edge detection. Or maybe there's a totally different option I could use. Ideally I was aiming more for only edges to the air to be outlined so the archways bottom edges would not be outlined like they are now


Making a Camera look at a target Vector I have a camera that works as long as its stationary. Now I'm trying to create a child class of that camera class that will look at its target. The new addition to the class is a method called SetTarget(). The method takes in a Vector3 target. The camera wont move but I need it to rotate to look at the target. If I just set the target, and then call CreateLookAt() (which takes in position, target, and up), when the object gets far enough away and underneath the camera, it suddenly flips right side up. So I need to transform the up vector, which currently always stays at Vector3.Up. I feel like this has something to do with taking the angle between the old direction vector and the new one (which I know can be expressed by target position). I feel like this is all really vague, so here's the code for my base camera class public class BasicCamera Microsoft.Xna.Framework.GameComponent public Matrix view get protected set public Matrix projection get protected set public Vector3 position get protected set public Vector3 direction get protected set public Vector3 up get protected set public Vector3 side get return Vector3.Cross(up, direction) protected set public BasicCamera(Game game, Vector3 position, Vector3 target, Vector3 up) base(game) this.position position this.direction target position this.up up CreateLookAt() projection Matrix.CreatePerspectiveFieldOfView( MathHelper.PiOver4, (float)Game.Window.ClientBounds.Width (float)Game.Window.ClientBounds.Height, 1, 500) public override void Update(GameTime gameTime) TODO Add your update code here CreateLookAt() base.Update(gameTime) And this is the code for the class that extends the above class to look at its target. class TargetedCamera BasicCamera public Vector3 target get protected set public TargetedCamera(Game game, Vector3 position, Vector3 target, Vector3 up) base(game, position, target, up) this.target target public void SetTarget(Vector3 target) direction target position protected override void CreateLookAt() view Matrix.CreateLookAt(position, target, up)


Dealing with 2D pixel shaders and SpriteBatches in XNA 4.0 component object game engine? I've got a bit of experience with shaders in general, having implemented a couple, very simple, 3D fragment and vertex shaders in OpenGL WebGL in the past. Currently, I'm working on a 2D game engine in XNA 4.0 and I'm struggling with the process of integrating per object and full scene shaders in my current architecture. I'm using a component entity design, wherein my "Entities" are merely collections of components that are acted upon by discreet system managers (SpatialProvider, SceneProvider, etc). In the context of this question, my draw call looks something like this SceneProvider Draw(GameTime) calls... ComponentManager Draw(GameTime, SpriteBatch) which calls (on each drawable component) DrawnComponent Draw(GameTime, SpriteBatch) The SpriteBatch is set up, with the default SpriteBatch shader, in the SceneProvider class just before it tells the ComponentManager to start rendering the scene. From my understanding, if a component needs to use a special shader to draw itself, it must do the following when it's Draw(GameTime, SpriteBatch) method is invoked public void Draw(GameTime gameTime, SpriteBatch spriteBatch) spriteBatch.End() spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, EffectShader, ViewMatrix) Draw things here that are shaded by the "EffectShader." spriteBatch.End() spriteBatch.Begin( same settings that were set by SceneProvider to ensure the rest of the scene is rendered normally ) My question is, having been told that numerous calls to SpriteBatch.Begin() and SpriteBatch.End() within a single frame is terrible for performance and creates a number of special cases for my drawing logic, is there a better way to do this? Is there a way to instruct the currently running SpriteBatch to simply change the Effect shader it is using for this particular draw call and then switch it back before the function ends?


Positioning a sprite in XNA Use ClientBounds or BackBuffer? I'm reading a book called "Learning XNA 4.0" written by Aaron Reed. Throughout most of the chapters, whenever he calculates the position of a sprite to use in his call to SpriteBatch.Draw, he uses Window.ClientBounds.Width and Window.ClientBounds.Height. But then all of a sudden, on page 108, he uses PresentationParameters.BackBufferWidth and PresentationParameters.BackBufferHeight instead. I think I understand what the Back Buffer and the Client Bounds are and the difference between those two (or perhaps not?). But I'm mighty confused about when I should use one or the other when it comes to positioning sprites. The author uses for the most part Client Bounds both for checking whenever a moving sprite is of the screen and to find a spawn point for new sprites. However, he seems to make two exceptions from this pattern in his book. The first time is when he wants some animated sprites to "move in" and cross the screen from one side to another (page 108 as mentioned). The second and last time is when he positions a texture to work as a button in the lower right corner of a Windows Phone 7 screen (page 379). Anyone got an idea? I shall provide some context if it is of any help. Here's how he usually calls SpriteBatch.Draw (code example from where he positions a sprite in the middle of the screen page 35 ) spriteBatch.Draw(texture, new Vector2( (Window.ClientBounds.Width 2) (texture.Width 2), (Window.ClientBounds.Height 2) (texture.Height 2)), null, Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 0) And here is the first case of four possible in a switch statement that will set the position of soon to be spawned moving sprites, this position will later be used in the SpriteBatch.Draw call (page 108) Randomly choose which side of the screen to place enemy, then randomly create a position along that side of the screen and randomly choose a speed for the enemy switch (((Game1)Game).rnd.Next(4)) case 0 LEFT to RIGHT position new Vector2( frameSize.X, ((Game1)Game).rnd.Next(0, Game.GraphicsDevice.PresentationParameters.BackBufferHeight frameSize.Y)) speed new Vector2(((Game1)Game).rnd.Next( enemyMinSpeed, enemyMaxSpeed), 0) break


Physics from other games I'm making a platform engine with XNA Game Studio, and I've solved almost everything about colliding stuff. But now, I'm searching for good physics for the player, I'm trying to emulate characters from other games like Mario from Super Mario World, or MegaMan X... do you know a website or something, where the physics from that games are revealed? I remember seen a page with something like that. Or what's the process you think is the best to emulate physics from other games? Just trial and error? Thank you.


Fbx animation without bones or single skeleton SkinnedModel sample nicely shows how to import single root bone skeleton and run in XNA. My question are Is it possible to have animations played in XNA if there no bones are used in model (which can easily be done in 3dmax with auto key frames)? Is it possible to have multiple independent bones laying around, connected to independent meshes and animated, all played in XNA? Can SkinnedModelProcessor be downgraded to this level ?


Saving and retrieving high score data in XNA 4.0 I made a game in XNA 4.0 and now I need to save the points in a database or in a file (or in something else). My goal is to store and retrieve the highest score if I choose that option in the main menu. What I found on the internet is not complete, or whatever, useless for me. What techniques can I use with XNA to save and load data?


Minecraft like blocky clouds We are working on a minecraft like block based engine lib. Lately I've started working a blocky clouds as in minecraft So it appers that in minecraft, clouds are not procedural. I'm still looking if it is viable to procedurally generate blocky clouds. I tried something like but it doesn't quite fit for clouds. float octave1 SimplexNoise.noise(x 0.004f, 1000, z 0.004f) 0.5f float octave2 SimplexNoise.noise(x 0.003f, 1000, z 0.003f) 0.25f float octave3 SimplexNoise.noise(x 0.02f, 100, z 0.02f) 0.15f this.Clouds x, z (octave1 octave2 octave3 gt 0.6) Any ideas or suggestions?


How do I clear up artifacts between aligned faces when using AA in XNA 4.0? I'm working on a graphics engine that lets you walk around a world that is made up of cubes (voxel engine) and I'm having some difficulties getting the results I want. I'm not the best at 3D graphics, but I'm willing to learn. When I have anti aliasing turned off, the textures line up properly together on the surfaces, but when I turn it on, I see a lot of lines between each square face. I've taken a picture I've tried changing the mip map mag filter options on the sampler, but cannot get it to look right. I've tried increasing the quality of the textures, but that doesn't help either. When I use Linear TextureFilter but that just makes everything super blurry, and the edges are even more obvious. In fact many edges get some blurry white and dark color to them. Anisotropic doesn't help. Nothing I do seems to get rid of those lines in between faces when I have AA turned on. Anyone have any advice on where I would start looking? I'm assuming it's because all of the faces are individual, and not mixed together when they are next to each other. Not just the edges are being anti aliased. Not sure if I'm even on the right track with that thought. I'm using XNA 4.0 to do this.


Need help to find error in collision dection in XNA I really need some help to find the reason why not any of my Asteroids sprites are visible on the screen after I added som code to dedect collision. My suspect is that it has to do in the collision method and that the sprites are removed from the list from the beginning!? The Spaceship is visible. In my manager class I have this method for checking the collision public void CollisionControl(Spaceship spaceShip) for (int i 0 i lt asteroidList.Count() i ) if (asteroidList.ElementAt(i).Bounds().Intersects(spaceShip.Bounds())) asteroidList.RemoveAt(i) i And then from the Game1 class I call this manager from the Update Method like this asteroidManager.CollisionControl(spaceship) And finally in the SpaceShip class and the Asteroids Class I have this code Bounds public Rectangle Bounds() return new Rectangle((int)(position.X orgin.X), (int)(position.Y orgin.Y), texture.Width, texture.Height) return new Rectangle(0,0,60,60) Draw method public void Draw(SpriteBatch spriteBatch) spriteBatch.Draw(texture, position, new Rectangle(0,0, (int)texture.Width, (int)texture.Height) , Color.White, rotation, orgin, 1, SpriteEffects.None, 0) spriteBatch.Draw(texture, position, null, Color.White, rotation, orgin, 1, SpriteEffects.None, 0) Help is really preciated! I'm doing a hand in task that I need to complete soon! Thanks!


Scroller game level map advice I'm started a XNA project to make a game similar in gameplay to Super Spy Hunter on a NES, which is used as a feature reference. The first thing I thought of is how to store and display level. Currently I'm thinking of using some tile graphics editor and custom pipeline for drawing level. I'm not sure however, that all is possible to implement every feature of reference game, but at least it's a start. Question is, looking at a given gameplay video, can you think of any possibly better approach then to design level using a tiles? By "better approach" I mean which will be either easier to work with, which will be more "natural" for this kind of game. The doubt comes mainly from a huge technology gap between then (1990) and now. So there is possibility that using current cpu power this could be done easier. Update 1. As I continue study reference game and ashes999 correctly mentioned procedural generation also comes into my mind. I began to think game logic is something like (simplified) while next road section exist get road section data set road generation options (borders type, road type, etc) set road section lenght while not end of a section generate road apply pseudorandom eye candy stuff this all looks like a pretty good data driven algorithm.


Server Client position information exchanging I am doing small game in xna client server, there can be 50f per seconds, but i don't belive that each client has to sent 50 mesagges about only their position, and then get back from server, regular ping is 50ms so even if 20 messages per second then success, so how it is made that everyone see immediately that someone else changed its position?


Platform independent replacement for LuaInterface I'm currently working on a project in C XNA, however I'm planning to migrate this to MonoGame so that it can go onto more platforms. The problem is that I am currently using a lot of Lua, and for that in XNA, I am using LuaInterface. The issue I now have is that LuaInterface only runs on Windows because of the dlls that it requires, but I would like to make this project available on Linux and Macs as well. Does anyone know of a good alternative to LuaInterface that could slot into Mono quite nicely? Re writing the parts which are currently in Lua in another language wouldn't be too much of a problem, but I need to be able to use scripting as I want to make large portions of my game open to players for modding.


Squashing screen resolution in XNA I've made a game in 1920x1080 res in XNA, and I can't seem to find a way for the graphics device to squash the screen images to other resolutions like 1600x900 when played on different computers. How can I get my game to be in proportion, and fit on smaller screens with the same aspect ratio?


How to do multi agent 2d pathfinding when agents can block each other? I recently restarted on my long time game development project and had a few questions about how to improve my games AI. I am a little stuck on the best way to implement my Enemy path finding when there are multiple enemies that can collide with each other. Here is an example of the way my AI works at the moment. The melee enemy has the following states Aggressive Attacking Is in range of attacking player Aggressive Stuck Is trying to reach the player but blocked by a collision object Aggressive Clear Is trying to reach the player but is not blocked by a collision object Passive not currently looking for the player but if it moves in it's line of sight it will move to the aggressive state Currently I am using a uniform tile system. Here is the basics on how the pathing works. FIND PATH FROM ENEMY TO PLAYER IF BLOCKED BY A COLLISION TILE CALL A STAR ALGORITHM ELSE IF NO COLLISION ON PATH MOVE TO PLAYER I do this every frame. This seems to work ok, but things have got more complicated when I bring in multiple enemies. What would be the best way to achieve the following. Find a path for the enemy to the player when there are multiple enemies that can all collide with each other? If I just call A STAR it won't work correctly as the other enemies who are collision objects are also moving. Sorry I hope this made sense, any help would be great.


How do I export Daz3D characters into an XNA format? How do I export 3D animated characters created in Daz3D studio to a format suitable for inclusion in XNA video games? I'm looking for instructions on how to make sure weight, bones, vertices and materials are properly translated over into an XNA useable format.


Quad Rendering Issue I am fairly new to using Quads, so I'm not sure how I can properly describe this issue in all honesty or to even hazard a guess as to why it's happening, so I have a screenshot to illustrate. So the white lines are actually Quads, the Red lines are just rectangles. So if you can see the issue, for some reason every "now amp again" I will get this issue were I get this somewhat looking "dotted line" which will sometimes be a full end to end line. I'm not too sure what's causing this issue, I have a feeling it has something to do with the way I'm drawing the quads, I don't think it's an incorrect vertices purely because the because of the thickness of the line, this leads me to believe it's the rendering effect.CurrentTechnique.Passes 0 .Apply() device.DrawUserPrimitives lt VertexPositionColorTexture gt (PrimitiveType.TriangleStrip, vertices, 0, totalNumberOfQuads) This is the order I'm adding the vertices Top Left Segment Corner Top Right Segment Corner Bottom Left Segment Corner Bottom Right Segment Corner So after getting the vertices in the correct order, things are now even stranger, as this is an image of the current output Here's my Current Code, including the rendering http pastebin.com yK5yBZy0


Diamond Isometric Tile Picking C Xna I recently converted the display style of a isometric map from staggered to diamond and I can't figure out the tile picking process. I'm well aware of the other existing threads regarding this subject and I read all of them but I haven't figured out a solution (my concentration these days is a mess) I'm using a very basic system which consists of passing through all tiles and pick the one where the mouse points at (something like this Map.Tile.Intersects(mouse.Rect) ) and then with the help of a color map I pick the correct tile. But I don't like this system because is pretty inefficient compared to some mathematic solutions I saw and didn't understand. So here is the code I use to create the map int x 128 j int y 64 i int isoX (6 64) (x y) int isoY (x y) 2 128 is the tileWidth , 64 tileHeight and 6 64 is the xOffset And the coordinates are like this Can somebody give me some hints or explain what I should do ? Thank you.


Font library for XNA Is there a free type library kind of implementation available for XNA? I wish to use it on WP7, so it should be a managed code. I know can alternatively use spritefont, but I wish to know if other implementations exist for complex requirements.


How can I map regions on a world map image? I am trying to use a map of the real world, but I need to have a way to break it down by countries and regions. Ideally down to a province level. I figure that I'd need to be able to define polygonal regions on the image and export the points that represent the bounding polygon, so that I could check for clicks inside, and do other things with it. I'm having a hard time finding a tool that will let me do this, that is, load in an arbitrary image and start defining polygons on it to be exported. Or am I going about this the hard way? Using XNA Monogame currently if that matters in your answer. Thanks


Unable to generate standalone noise I've been stuck this evening on getting a Perlin Noise function to generate by itself. Every time I run the program without adding to different types of noise together it calls an ArgumentException error. Here is my code I'm using. perlin gen Random rand new Random() double freq 1 32.0 double lacu 3.0 int octave 5 double pers 0.5 int seed 1 Perlin perlin new Perlin(freq, lacu, pers, octave, seed, QualityMode.High) init the noise map noiseMap new Noise2D(128, 128) noiseMap.GeneratePlanar(1, 2, 1, 2, true) And the error that it calls is here. public void GeneratePlanar(double left, double right, double top, double bottom, bool seamless) if (right lt left bottom lt top this.m generator null) throw new ArgumentException() I've checked and re checked the code multiple times, so I'm not sure what is going on that is making the GeneratePlanar function call the ArgumentException error.


Where should I place my reaction code in Per Pixel Collision Detection? I have this collision detection code public bool PerPixelCollision(Player player, Game1 dog) Matrix atob player.Transform Matrix.Invert(dog.Transform) Vector2 stepX Vector2.TransformNormal(Vector2.UnitX, atob) Vector2 stepY Vector2.TransformNormal(Vector2.UnitY, atob) Vector2 iBPos Vector2.Transform(Vector2.Zero, atob) for(int deltax 0 deltax lt player.playerTexture.Width deltax ) Vector2 bpos iBPos for (int deltay 0 deltay lt player.playerTexture.Height deltay ) int bx (int)bpos.X int by (int)bpos.Y if (bx gt 0 amp amp bx lt dog.dogTexture.Width amp amp by gt 0 amp amp by lt dog.dogTexture.Height) if (player.TextureData deltax deltay player.playerTexture.Width .A gt 150 amp amp dog.TextureData bx by dog.Texture.Width .A gt 150) return true bpos stepY iBPos stepX return false What I want to know is where to put in the code where something happens. For example, I want to put in player.playerPosition.X 200 just as a test, but I don't know where to put it. I tried putting it under the return true and above it, but under it, it said unreachable code, and above it nothing happened. I also tried putting it by bpos stepY but that didn't work either. Where do I put the code?


XNA just a few more characters accepted in a SpriteFont I have a SpriteFont in XNA, which has the standard 126 characters that are usable. However i would like to use the " " symbol in the game. So is there anyway of adding just a few more symbols that the spritefont accepts? Cheers, Randomman159


Is XNA for iOS overkill? I'm working on iPAD game using MonoTouch which is similar to an IQ testing game. At the moment, I can write some simple games using basic UIImages and animations. I'm wondering if I should learn XNA to create a game where people can throw a ball against a wall and see it bounce. Has anyone seen any good examples of tutorials using XNA for simple 2d games?