How can I normalize a vector if I am handling movment of each axis seperatley? I am writing a 2D tile based game engine in XNA, and I've recently fine tuned my collision detection using the answers provided here and more specifically here. The tile based collision detection now works flawlessly and fixed all the small problems I had with my previous code. However, implementing this forced me to rewrite how movement was handled. Instead of moving the player all at once and then resolving each collision along the smallest axis of intersection depth, it now updates and resolves on the X and Y axes separately. This is fine, but now my diagonal movement is much faster than my horizontal and vertical movement and I am unsure of how to normalize it. I'm sure I'm just overlooking something simple, is there a straight forward way of doing this? public void HandleInput() Set horizontal and vertical values accordingly based on direction of key presses int horizontal InputHelper.IsKeyDown(Keys.A) ? 1 (InputHelper.IsKeyDown(Keys.D) ? 1 0) int vertical InputHelper.IsKeyDown(Keys.W) ? 1 (InputHelper.IsKeyDown(Keys.S) ? 1 0) If there is movement update sprite position, round the position to nearest pixel and then check for collision if (vertical ! 0) sprite.Position Vector2.UnitY sprite.Speed vertical sprite.Position new Vector2(sprite.Position.X, (float)Math.Round(sprite.Position.Y)) HandleCollisions(Direction.Vertical) UpdateSpriteAnimation(Direction.Vertical, vertical) if (horizontal ! 0) sprite.Position Vector2.UnitX sprite.Speed horizontal sprite.Position new Vector2((float)Math.Round(sprite.Position.X), sprite.Position.Y) HandleCollisions(Direction.Horizontal) UpdateSpriteAnimation(Direction.Horizontal, horizontal) private void HandleCollisions(Direction direction) Get the player's bounding rectangle and find neighboring tiles. Rectangle playerBounds sprite.spriteBounds int leftTile playerBounds.Left Engine.TileSize int topTile playerBounds.Top Engine.TileSize int rightTile (int)Math.Ceiling((float)playerBounds.Right Engine.TileSize) 1 int bottomTile (int)Math.Ceiling(((float)playerBounds.Bottom Engine.TileSize)) 1 For each potentially colliding tile, for (int y topTile y lt bottomTile y) for (int x leftTile x lt rightTile x) Vector2 depth If this tile is collidable, and it intersects sprite bounds if (tileMap.CollisionLayer.GetCellIndex(x, y) 0 amp amp TileIntersectsPlayer(playerBounds, GetTileBounds(y, x), direction, out depth)) Resolve the collision along the given axis sprite.Position depth Perform further collisions with the new bounds. playerBounds sprite.spriteBounds


My grid based collision detection is slow Something about my implementation of a basic 2x4 grid for collision detection is slow so slow in fact, that it's actually faster to simply check every bullet from every enemy to see if the BoundingSphere intersects with that of my ship. It becomes noticeably slow when I have approximately 1000 bullets on the screen (36 enemies shooting 3 bullets every .5 seconds). By commenting it out bit by bit, I've determined that the code used to add them to the grid is what's slowest. Here's how I add them to the grid for (int i 0 i lt enemy x .gun.NumBullets i ) if (enemy x .gun.bulletList i .isActive) enemy x .gun.bulletList i .Update(timeDelta) int bulletPosition 0 if (enemy x .gun.bulletList i .position.Y lt 0) bulletPosition (int)Math.Floor((enemy x .gun.bulletList i .position.X 900) 450) else bulletPosition (int)Math.Floor((enemy x .gun.bulletList i .position.X 900) 450) 4 GridItem bulletItem new GridItem() bulletItem.index i bulletItem.type 5 bulletItem.parentIndex x if (bulletPosition gt 1 amp amp bulletPosition lt 8) if (!grid bulletPosition .Contains(bulletItem)) for (int j 0 j lt grid.Length j ) grid j .Remove(bulletItem) grid bulletPosition .Add(bulletItem) And here's how I check if it collides with the ship if (ship.isActive amp amp !ship.invincible) BoundingSphere shipSphere new BoundingSphere( ship.Position, ship.Model.Meshes 0 .BoundingSphere.Radius 9.0f) for (int i 0 i lt grid.Length i ) if (grid i .Contains(shipItem)) for (int j 0 j lt grid i .Count j ) Other collision types omitted else if (grid i j .type 5) if (enemy grid i j .parentIndex .gun.bulletList grid i j .index .isActive) BoundingSphere bulletSphere new BoundingSphere(enemy grid i j .parentIndex .gun.bulletList grid i j .index .position, enemy grid i j .parentIndex .gun.bulletModel.Meshes 0 .BoundingSphere.Radius) if (shipSphere.Intersects(bulletSphere)) ship.health enemy grid i j .parentIndex .gun.damage enemy grid i j .parentIndex .gun.bulletList grid i j .index .isActive false grid i .RemoveAt(j) break no need to check other bullets else grid i .RemoveAt(j) What am I doing wrong here? I thought a grid implementation would be faster than checking each one.


How can I remove Magic Pink from an image at runtime using GraphicsDevice? In XNA 4.0, I want to load all my textures at runtime, which means I will not be able to take advantage of the content processor. (This is fine because it would allow people to change graphics and other elements without having to have XNA installed to compile them into .xnb) Suppose that I can't (or don't want to) use premultiplied alpha on my images, and instead rely on the classic magic pink (255, 0, 255) method How can I turn it into a Texture2D object and convert the pink to be transparent using GraphicsDevice? It is trivial to iterate the data with GetData() and SetData(), but this uses the processor, rather than the graphics card.


Specific bone not present in the skeleton XNA I have created a human mesh, bone structure, and animation rig in 3ds max for an XNA game I am developing for school. I am currently having a problem with one specific bone upon build in Visual Studio. It's the 3rd bone of the right pinky and I have promptly named it "The Problem Bone". The build is giving me this error Vertex is bound to bone "The Problem Bone", but this bone is not present in the skeleton. I've checked the skeleton many times to confirm that the bone does exist. The skeleton hierarchy root is the pelvis bone and I verified that no bone was being ignored due to the mesh having more than one skeleton which is usually the cause of this problem. After reading the .fbx file, I found that the XNA was building the bones starting with the pelvis, then going down the right leg, then the left leg, then the spine up to the head, and then the right arm which where my problem area is. As we can see in the schematic view, the problem bone is linked to a previous successfully built bone. The bones are controlled by splines, point helpers, and IK chains through linking and constraining. I don't think that these are the problem since other bones driven by the controllers were successfully built before the problem bone. So the other bones up until the 3rd bone of the right pinky are being built correctly which gives me the feeling that I'm close to a solution and it's something small impeding my progress. Does anyone know why I am getting this error? Exporting from 3ds Max Process Select only the bones and the mesh File Export Export Selected Save as .fbx Current .fbx export dialog window


Am I going to regret using a color based collision detection system? I'm just getting started build my first game with XNA (I'm experienced with C but not games). I'm building a pretty simple top down 2d shooter. I read this tutorial on using a color based collision system and it sounded really cool to me. http www.xnadevelopment.com tutorials theroadnottaken theroadnottaken.shtml It means I can quickly make levels just using any graphics program and not have to define my scenery (walls, trees etc) in terms of collision boxes etc right? However I can see that going down this path means that perhaps the calculation for determining whether fast moving objects like bullets intersect walls etc becomes more difficult potentially because you cant' do basic geometry intersection type calcs. Is that right? Am I going to regret going in this direction if my game gets more complex over time? Worth just investing in the creation of a level editor to define my scenery in terms of geometry? Any advice for a noob very much appreciated!


Xbox Controller Not Connecting in Monogame Project I have recently been playing around with the support of the wired XBox 360 controller in Windows development. I am developing in C in Visual Studio 2012. I have created 2 projects. The first (Project A) is an XNA project compiled in .Net 4.0. The second (Project B) is a MonoGame 3.0 Windows Open GL project also compiled in .Net 4.0. My issue is that my wired Xbox 360 controller can only be picked up in Project A the XNA project. I would really like to continue working with the Monogame type, but have hit a brick wall here. I have verified that all the requisite libraries (OpenTK, Tao.SDL, SDL) are the exact same files being referenced by both projects. Still, the Monogame project does not pick up the controller. The exact state of the GamePadState variable is Connected false. Any ideas? Again, same computer, same code for accessing the controller, only difference is XNA vs Monogame.


Loading SpriteFont through a different class than Game.cs I am trying to load up a single SpriteFont to print some debug information. In our current game, we load up both Textures and Music through a ResourceManager. They are both loaded with a filestream, and thus do not require Content.Load SoundEffect soundEffect SoundEffect.FromStream( fs ) Since this ResourceManager does not inherit from Game or is like Game.cs, I cannot use the usual method SpriteFont spriteFont Content.Load lt SpriteFont gt (resource.Key.Item2) Anyone have any idea how I can either Load the SpriteFont a different way Create my own Contentmanager


Texture not carrying over to game correctly? I have created my map for my game using 3DS Max. I have then applied textures to the map within 3DS Max, where the textures all show correctly. I export the map as a .fbx file to use within an XNA project. However as you can see from the below screenshot, the textures are not displayed correctly in XNA. Does anyone know why this is happening? I am using the Autodesk FBX content importer and the Model XNA Framework Content Processor. As you can see my model which was created in the same way has the textures displayed correctly, it is only doing it to my map.


How do I avoid pathfinding characters getting stuck in corners? I used A pathfinding to return a list of Tiles to get from an enemy to the player. After that, I wasn't sure how to actually move the enemy. What I ended up doing was get the first Tile in the path. Then, check all 8 directions from the enemy's current tile. If the path tile is in the enemy tile's adjacent bottom square, move like this. If it's the right square, do that, etc. When the tile of the enemy is the same as that tile in the path, remove it from the path, and repeat for the next one. This works, except my character sometimes gets caught around corners. This is because it thinks it should be moving horizontally (the next tile in the path is above it) when it's actually more of a diagonal movement to actually get to it. I need to know two things Is there a better way I should do the movement after calculating the tiles in the path? What are some ways to deal with the corners and diagonals? I was thinking perhaps some sort of random movement, but it's kind of janky. In the end, don't care how silly it is as long as the enemy doesn't get stuck! Really new to all of this, so would appreciate some advice!


Loading textures as a method I want to load a texture when I need it, so I'd need a method in order to do so. LoadTexture(string fileName) I'd only use that one parameter, but what would I put in the method? So far I've only ever loaded content at startup with something like content.Load lt Texture2D gt ("blah") But I want to move away from loading everything at startup and only load content when I need it. EDIT In order to explain what I'm going for, I'll give more detail. Say I have a chunk of blocks 50x50x50. Most of these won't be drawn, so it doesn't make sense to load the texture for the cubes not drawn. This is why I want a method that I can call whenever the texture needs to be loaded for the cube. Instead of loading 6 textures for 6 sides for 125,000 cubes, I cut back the amount of loading to only the visible cubes.


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


What is the correct object orientated approach to class design in game development? I'm in the midst of developing a 2D sprite based game for Windows 7 Phone, using XNA. The training and tutorials available for it are pretty helpful, but the problem I face is that each of them approaches their class design differently, and the code is not particularly well factored. As a result, it has been difficult for me to gain a good understanding of which responsibilities I should give to a particular class. For example, I could have a base sprite class BaseSprite that knows how to draw itself, check for collisions, etc. I could then have an AnimatedSprite class that would know how to navigate its sprite sheet, an ExplodingSprite class, and so on. This technique is demonstrated in the Space Invaders example in the Windows 7 Phone Jumpstart Session 2 materials. Alternatively, I could instead place the bulk of rendering and running the game responsibility in a GameScreen class that class and its derived classes behave more like forms or web pages in terms of their responsibilities. Sprite classes are more simple containers with much less logic. This is the technique used in the Windows 7 Phone Training Kit's Alien Sprite game and other game state manager examples. What is the correct object orientated approach to class design in game development?


How to make a wait timer? I am making a mining styled game and am looking to make variables that effect how fast you are able to mine the block. This is the idea I have currently got but it does not wait for the timer to complete before mining, has anyone got a better way to do this? if (MinePlayerCollision() amp amp newState.IsKeyDown(Keys.D)) MiningElapsed (float) gameTime.TotalGameTime.Seconds if (MiningEff lt MiningElapsed) BlockMined true MineReset false MiningElapsed 0


Calculating the correct particle angle in an outwards explosion I'm creating a simple particle explosion but am stuck in finding the correct angle to rotate my particle. The effect I'm going for is similar to this Where each particle is going outwards from the point of origin and at the correct angle. This is what I currently have As you can see, each particle is facing the same angle, but I'm having a little difficulty figuring out the correct angle. I have the vector for the point of emission and the new vector for each particle, how can I use this to calculate the angle? Some code for reference private Particle CreateParticle() ... Vector2 velocity new Vector2(2.0f (float)(random.NextDouble() 2 1), 2.0f (float)(random.NextDouble() 2 1)) direction velocity ParticleLocation float angle (float)Math.Atan2(direction.Y, direction.X) ... return new Particle(texture, position, velocity, angle, angularVelocity, color, size, ttl, EmitterLocation) I am then using the angle created as so in my particles Draw method spriteBatch.Draw(Texture, Position, null, Color, Angle, origin, Size, SpriteEffects.None, 0f)


Hide original video file in XNA game I want to play some videos in my XNA game. I have looked at this tutorial. I have tried it. It creates XNB file but also copies original WMV file into output content directory. Is there some simple solution, how can I pack hide original WMV file? I don't want user get it. Thanks for any help.


Xna menu navigation with controller I have a menu that you can navigate with the keyboard, but I also want it so you can navigate it with the controller thumb sticks. But my problem is that if you push down or up on the thumb sticks it will just fly through the menu. To fix problem if it was a keyboard you would just do prevKeyState.IsKeyUp(Keys.Down). So I was wondering if there anything like this for the controller thumb sticks? I'm not sure if I'm doing something wrong but it still flies through the menu. private enum GamePadStates None, GoingDown, GoingUp GamePadStates CurrentGamePad, PreviousGamePad GamePadStates.None public void Update(GameTime gameTime) keyState Keyboard.GetState() gamePadState GamePad.GetState(PlayerIndex.One) PreviousGamePad CurrentGamePad if (gamePadState.ThumbSticks.Left.Y gt 0.1) CurrentGamePad GamePadStates.GoingUp else if (gamePadState.ThumbSticks.Left.Y lt 0.1) CurrentGamePad GamePadStates.GoingDown else CurrentGamePad GamePadStates.None if (keyState.IsKeyDown(Keys.Down) amp amp prevKeyState.IsKeyUp(Keys.Down) CurrentGamePad GamePadStates.GoingDown amp amp PreviousGamePad ! GamePadStates.GoingUp) if (selected lt (buttonList.Count 1)) selected if (keyState.IsKeyDown(Keys.Up) amp amp prevKeyState.IsKeyUp(Keys.Up) CurrentGamePad GamePadStates.GoingUp amp amp PreviousGamePad ! GamePadStates.GoingDown) if (selected gt 0) selected


Higher Performance With Spritesheets Than With Rotating Using C and XNA 4.0? I would like to know what the performance difference is between using multiple sprites in one file (sprite sheets) to draw a game character being able to face in 4 directions and using one sprite per file but rotating that character to my needs. I am aware that the sprite sheet method restricts the character to only be able to look into predefined directions, whereas the rotation method would give the character the freedom of "looking everywhere". Here's an example of what I am doing Single Sprite Method Assuming I have a 64x64 texture that points north. So I do the following if I wanted it to point east spriteBatch.Draw( sampleTexture, new Rectangle(200, 100, 64, 64), null, Color.White, (float)(Math.PI 2), Vector2.Zero, SpriteEffects.None, 0) Multiple Sprite Method Now I got a sprite sheet (128x128) where the top left 64x64 section contains a sprite pointing north, top right 64x64 section points east, and so forth. And to make it point east, i do the following spriteBatch.Draw( sampleSpritesheet, new Rectangle(400, 100, 64, 64), new Rectangle(64, 0, 64, 64), Color.White) So which of these methods is using less CPU time and what are the pro's and con's? Is .NET XNA optimizing this in any way (e.g. it notices that the same call was done last frame and then just uses an already rendered rotated image thats still in memory)?


XNA UV Mapping flipping the Texture every second time I am making a tile based game. Recently I moved to drawing tiles as primitives to speed up things and also allow for easier lighting (Vertex Shader). I then took it a step further and made some calculations to "merge" together tiles into the same primitive to gain even more performance, and to get around UV texture problems I simply did this... if (!top) Adds the top vertices thisquad.Vertices 0 new VertexPositionTexture(new Vector3(new Vector2(p.X, p.Y), 0), new Vector2(0, 0)) thisquad.Vertices 1 new VertexPositionTexture(new Vector3(new Vector2(Tile.Size p.X, p.Y), 0), new Vector2(1, 0)) top true Extends the bottom vertices thisquad.Vertices 2 new VertexPositionTexture(new Vector3(new Vector2(p.X, Tile.Size p.Y), 0), new Vector2(0, currentquadtilecount)) thisquad.Vertices 3 new VertexPositionTexture(new Vector3(new Vector2(Tile.Size p.X, Tile.Size p.Y), 0), new Vector2(1, currentquadtilecount)) currentquadtilecount With currentquadtilecount starting at 1, if a tile is floating on its own it will display the texture properly, but for every second tile that merges, the texture is flipped. As shown below... What am I doing wrong? Is this even the right way to do this?? Twitchy


Effective AI for 3D Motion I am developing a game in XNA and am trying to create an effective AI for the enemy and friendly spaceships but am having a hard time keeping the game effective without disadvantaging one side or the other (deliberately). My current setup is as follows Ship targets enemy based on proximity. Ship changes direction and moves toward target, firing when in range. Ship fires single repeater weapon in the forward direction. Ship will not change direction when closer than certain distance from enemy. If you are directly following and shooting at a ship, the ship does not attempt to evade fire. (consequence of 3) All ships have similar firepower. I am trying to improve this system and am willing to rewrite if necessary. Most of the ships end up flying around each other, shooting but never hitting. I have thought of several ideas to improve it Once health drops significantly, ship will boost away from firing ship. Some ships are randomly chosen to be equipped with torpedoes (maybe add aft firing?). Make ships more wary of attacking cruisers (they tend to die quickly when attacking). Does anyone have any other suggestions as to improve the AI of the ships? Does anyone have a completely different system of doing this?


Render error in xna DrawPrimitive for Assimp Mesh I am trying to render the vertices of a scene with a cube I exported as an OBJ from Blender. The 8 vertices become 24 when imported into XNA but when I render it I dont see all faces. This is not an issue of missing meshes because I'm pretty sure this is being stored as the first and only mesh. I suspect this is because of the vectors defined in the Assimp Mesh object but I can't seem to find any help for this. THIS IS SOLVED! The code shows how to render a 3D model using only Assimp and XNA with vertex and index buffers. oScene is the Scene object imported using Assimp. This code only draws faces in a single color without textures. Here is the relevant code private void SetUpVertices() mMesh oScene.Meshes 0 vertices new VertexPositionColor mMesh.VertexCount indices new short mMesh.FaceCount 3 int i 0 foreach (Vector3D mVec in mMesh.Vertices) vertices i new VertexPositionColor(new Vector3(mVec.X, mVec.Y, mVec.Z), Color.Red) i int f 0 Face mFace for (i 0 i lt mMesh.FaceCount 3 i i 3) mFace mMesh.Faces f f indices i (short)mFace.Indices 0 indices i 1 (short)mFace.Indices 1 indices i 2 (short)mFace.Indices 2 vertexBuffer new VertexBuffer(device, VertexPositionColor.VertexDeclaration, vertices.Length, BufferUsage.WriteOnly) vertexBuffer.SetData(vertices) indexBuffer new IndexBuffer(device, typeof(short), indices.Length, BufferUsage.None) indexBuffer.SetData(indices) private void SetUpCamera() cameraPos new Vector3(0, 5, 9) viewMatrix Matrix.CreateLookAt(cameraPos, new Vector3(0, 0, 1), new Vector3(0, 1, 0)) projectionMatrix Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, device.Viewport.AspectRatio, 1.0f, 200.0f) protected override void Draw(GameTime gameTime) device.Clear(ClearOptions.Target ClearOptions.DepthBuffer, Color.DarkSlateBlue, 1.0f, 0) effect new BasicEffect(GraphicsDevice) effect.VertexColorEnabled true effect.View viewMatrix effect.Projection projectionMatrix effect.World Matrix.Identity foreach (EffectPass pass in effect.CurrentTechnique.Passes) pass.Apply() device.SetVertexBuffer(vertexBuffer) device.Indices indexBuffer device.DrawIndexedPrimitives(Microsoft.Xna.Framework.Graphics.PrimitiveType.TriangleList, 0, 0, oScene.Meshes 0 .VertexCount, 0, mMesh.FaceCount) base.Draw(gameTime)


Figuring out what object is closer to a certain point? I'm trying to create fog of war, I have the visual effect created but I'm not sure how to deal with the hiding of other players if they're within the fog of war. So right now the thing I'm trying to do is if another player is hiding behind a wall then not to render that player. I was thinking of doing it by sending a ray in the direction of all the players, and then creating a list of all the obstacles that ray collides with and then trying to figure out if an obstacle was closer than the player in order to predict the distance. But then I realized I'm not really sure how to figure out if the obstacle is infact closer or not because I have to account for all the dimensions, so I'm kind of stuck. First of all is this approach the correct way to go about it and secondly how would I calculate if the obstacle was infact closer taking into account the X Y and Z. Thanks


XNA Check if the sound is playing Quick question I have a SoundEffect instance, and I would like to know if it is playing at the moment or not. But there's neither a method, nor a property that would allow to check it... So, is there a way to know it?


how do I make an enemy target an ally unit? I have 2 different classes, a EnemyFighter class, and a EnemyBomber class. both are planes that I have that can fly around the map.( i also have AllyFighter, and AllyBomber) So far they can follow me, and eachother, but how would I set up a target variable or something? like I could set up a target variable for the enemyfighter AllyFighter target and a variable holding the location of the allyfighter as a Vector2. but then what if I want to target an AllyBomber? do I have to make 2 variables? or is there some other approach I should take? Thanks EDIT Maybe a better question would be how can I target different enemy types (ones with different classes)? or at least hold there information in a 'target' variable


Run XNA game without graphics Wondering if there is anyway to run an XNA game with out displaying anything. I have a working game that runs in a client server setup where one player is the host and other people can connect to his game. I now want to be able to run the game as a host on a decicated server with no graphics card, basically I dont want to run any Draw() logic at all. Do i really need to go through the entire game and remove all references to XNA? How have people done this? EDIT The reason I want to do this is because I have a working client server setup in the game and I dont want to make a separate "headless" server program.


How do I implement 2D shadows cast between layers? How could I implement 2d shadows that are cast by objects in a different layer? NOT like the dynamic lighting in the well known tutorial from Catalin Zima But like the shadows of the pipes in this video And like the shadow of the platform and the character in this video I would like to use the same kind of lighting in a scene with many layers and a lot of lights with different colors. I could imagine doing this by drawing a black copy of the layer over the layers behind that layer, and adjusting it according to holes in the layers on which the shadow is cast. But I hope there is a less expensive, pixel shader based approach for this.


2D Camera Acceleration Lag I have a nice camera set up for my 2D xna game. Im wondering how I should make the camera have 'acceleration' or 'lag' so it smoothly follows the player, instead of 'exactly' like mine does now. Im thinking somehow I need to Lerp the values when I set CameraPosition. Heres my code private void ScrollCamera(Viewport viewport) float ViewMargin .35f float marginWidth viewport.Width ViewMargin float marginLeft cameraPosition.X marginWidth float marginRight cameraPosition.X viewport.Width marginWidth float TopMargin .3f float BottomMargin .1f float marginTop cameraPosition.Y viewport.Height TopMargin float marginBottom cameraPosition.Y viewport.Height viewport.Height BottomMargin Vector2 CameraMovement Vector2 maxCameraPosition CameraMovement.X 0.0f if (Player.Position.X lt marginLeft) CameraMovement.X Player.Position.X marginLeft else if (Player.Position.X gt marginRight) CameraMovement.X Player.Position.X marginRight maxCameraPosition.X 16 Width viewport.Width cameraPosition.X MathHelper.Clamp(cameraPosition.X CameraMovement.X, 0.0f, maxCameraPosition.X) CameraMovement.Y 0.0f if (Player.Position.Y lt marginTop) above the top margin CameraMovement.Y Player.Position.Y marginTop else if (Player.Position.Y gt marginBottom) below the bottom margin CameraMovement.Y Player.Position.Y marginBottom maxCameraPosition.Y 16 Height viewport.Height cameraPosition.Y MathHelper.Clamp(cameraPosition.Y CameraMovement.Y, 0.0f, maxCameraPosition.Y)


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


XNA C Shadows look strange in orthographic I have implemented shadows in to my game engine. They look fine when rendered in projection mode as a projected light, however I get a strange "blocky" look when they are put into orho'. I will be rendering much bigger scenes (MMO size maps, for example) and Ive heard that rendering in orthographic for the shadow map will give a better result, and it does in some ways. I dislike rendering with projective perspective as you can see the view frustum, whereas this doesnt happen with orthographic. Here is the code I have for rendering every update public void UpdateLightData() Matrix lightsView Matrix lightsProjection ambientPower 0.2f lightPower 2f cameraFrustum.Matrix player.view player.projection lightPos new Vector3(0, 30, 0) lightsView Matrix.CreateLookAt(lightPos, new Vector3( 2, 3, 10), new Vector3(0, 1, 0)) lightsProjection Matrix.CreateOrthographic(Globals.device.Viewport.Width, Globals.device.Viewport.Height, 0.1f, 100f) lightsProjection Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver2, 1f, 5f, 100f) lightsViewProjectionMatrix lightsView lightsProjection Here is a screenshot of ProjectionPerspective https www.dropbox.com s yen671frsft4kdl Screenshot 202015 03 07 2016.00.32.png?dl 0 Here is what it looks like in orthographic https www.dropbox.com s jj6h4zgodda38fe Screenshot 202015 03 07 2016.01.19.png?dl 0


Add a "fake" Loading Screen I'm working on a 2D game for WPF8 using XNA 4.0. Everything goes great, but it's too fast. I was just wondering, what could I do between the end of the game and the score screen, and before the game starts? I'm looking for a sample of how to do that (black screen with "loading" write in windows phone style) or a way to implement it.


Why does RGB order differ between color formats? On the reference page for SurfaceFormat, it indicates that the Bgra4444 format is an unsigned format which is 16 bits long, with 4 bits per color with alpha. Further down the page, it describes the Rgba64 format as being 64 bits long, with 16 bits per color (including alpha). Why does one format list R G B as the color order, while the other lists it as B G R? I understand it likely has to do with the underlying hardware, but there certainly needs to be a reason that it wants it in a reversed order for the other format.


Is there a way to write a camera class without matrix transformation? I have a problem with a camera class I got from the internet. It does a transformation like this public Matrix get transformation(GraphicsDevice graphicsDevice) transform Matrix.CreateTranslation(new Vector3( pos.X, pos.Y, 0)) Matrix.CreateRotationZ(Rotation) Matrix.CreateScale(new Vector3(Zoom, Zoom, 1)) Matrix.CreateTranslation(new Vector3(ViewportWidth 0.5f, ViewportHeight 0.5f, 0)) return transform Later the spritebatch is called like this spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, null, cam.get transformation(device)) The problem is that at this point the mouse coordinates are not relative anymore to the other sprites I draw. This is a problem because I try detect which sprite has been clicked. I understand that this issue can be solved by considering the following picture This was posted in a very good awnser before, here. But somehow this does not really help me. So my question is Is there a way to create a Camera class which does not use transformation, can be moved with keys and keeps the viewport coordinates relative? Thanks in advance!


C Perlin noise generating endless terrain chunks? I'm currently writing a little side scroller in C , to both learn C and have fun. Right now I have a simple random number generator generating the world but it isn't exactly all that great so with some research, I've discovered that Perlin Noise generation may help me out quite a bit. Problem is, I want to have an "endless" landscape made up of several chunks. Basically my questions concerns are Using minecraft as an example (Ignoring the 3rd dimension), how is Notch getting each chunk to connect to each other perfectly? Tunnels, caves, ore veins, mountains, flat lands, biomes, etc. are all connected to each other even though each chunk is generated separately, and sometimes at a much later date. This is key for me, I want the player to be able to walk to the right and as they are walking, generate more landscape that connects to previous landscape, including underground tunnels and cave systems. Going off of 1, how would this be accomplished under the assumption that each chunk is a square, and the world is 10 squares high, and infinite squares wide? I.e. Each "chunk" is 128x128 tiles and the world is 1,280 tiles tall total. (This is so that I can make an infinitely deep map if I choose to and also to show that all 4 sides of a chunk square need to be able to connect and continue on what the previous square chunk was doing).


Working with lots of cubes. Improving performance? Edit To sum the question up, I have a voxel based world (Minecraft style (Thanks Communist Duck)) which is suffering from poor performance. I am not positive on the source but would like any possible advice on how to get rid of it. I am working on a project where a world consists of a large quantity of cubes (I would give you a number, but it is user defined worlds). My test one is around (48 x 32 x 48) blocks. Basically these blocks don't do anything in themselves. They just sit there. They start being used when it comes to player interaction. I need to check what cubes the users mouse interacts with (mouse over, clicking, etc.), and for collision detecting as the player moves. Now I had a massive amount of lag at first, looping through every block. I have managed to decrease that lag, by looping through all the blocks, and finding which blocks are within a particular range of the character, and then only looping through those blocks for the collision detection, etc. However, I am still going at a depressing 2fps. Does anyone have any other ideas on how I could decrease this lag? Btw, I am using XNA (C ) and yes, it is 3d.


Can you store negative numbers with XNA HLSL? I am trying to make a ripple effect with a HLSL shader, it works so far but I need to output negative numbers and that won't work for the calculations. Is there some way to do this with the SurfaceFormat class? By the way I am rendering 2 RenderTarget2D classes. This is how I calculate it float4 add float4(0,0,0.5,0) float4 input tex2D( BaseSampler, Tex) float4 cur tex2D( RippleSampler, Tex) float curY 0 float curX cur.x float tempCurY cur.y curY (tex2D( RippleSampler, float2(Tex.x pixelSizeX, Tex.y)).x tex2D( RippleSampler, float2(Tex.x pixelSizeX, Tex.y)).x tex2D( RippleSampler, float2(Tex.x , Tex.y pixelSizeY)).x tex2D( RippleSampler, float2(Tex.x , Tex.y pixelSizeY)).x) 0.5f tempCurY curY damping if(curY lt 0.01f) cur float4(curX,curY input.x,0.5,1) else cur float4(curX,curY,0.5,1) return cur


How do I create a 3rd person camera? I currently have a camera class set up and have my model player loaded but I can't get my camera in the correct position by changing the x,y,z coordinates. I have set up my "game" with a separate class for the model player and a class for the camera. I am fairly new to XNA and most of what I have already got is from a tutorial from my lecturer. Here is my player model class public class Player public Model model public Matrix world Matrix.Identity public Vector3 position public Vector3 direction public Quaternion rotation Quaternion.Identity public BoundingSphere collision public float speed 2f public float moveForwards public float moveLeft public float forward Matrix transform public Player(Model m, Vector3 iPos) model m position iPos direction new Vector3(0, 0, 1) transform new Matrix m.Bones.Count m.CopyAbsoluteBoneTransformsTo(transform) foreach (ModelMesh mesh in m.Meshes) collision BoundingSphere.CreateMerged(collision, mesh.BoundingSphere) public Player() public BoundingSphere getSphere() return collision.Transform(world) public void sampleInputMovement(GamePadState player) moveForwards (player.ThumbSticks.Left.Y 5) moveLeft (player.ThumbSticks.Left.X 32) 1 public void update() rotation Quaternion.CreateFromAxisAngle(new Vector3(0, 0, 1), moveLeft) Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), moveForwards) Vector3 motion Vector3.Transform(direction, rotation) position motion forward world Matrix.CreateFromQuaternion(rotation) Matrix.CreateTranslation(position) public void Draw(Matrix projection, Matrix view) Matrix transforms new Matrix model.Bones.Count model.CopyAbsoluteBoneTransformsTo(transforms) foreach (ModelMesh mesh in model.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.EnableDefaultLighting() effect.Projection projection effect.View view effect.World transforms mesh.ParentBone.Index world mesh.Draw() And here is my camera class public class Camera Vector3 position Vector3 newposition Quaternion cameraRotation Vector3 targetOffset new Vector3(0, 1f, 6f) public Matrix view Matrix.Identity public Matrix projection Matrix.Identity public Camera(Game game, Vector3 xPostion) position xPostion projection Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, game.GraphicsDevice.Viewport.AspectRatio, 1.0f, 1000000f) public void update(Matrix targetWorld) Quaternion rotation Vector3 target Vector3 scale targetWorld.Decompose(out scale, out rotation, out target) cameraRotation Quaternion.Lerp(cameraRotation, rotation, 0.15f) newposition Vector3.Transform(targetOffset, targetWorld) position Vector3.SmoothStep(position, newposition, 0.8f) Vector3 cameraup Vector3.Transform(new Vector3(0, 1, 0), Matrix.CreateFromQuaternion(cameraRotation)) view Matrix.CreateLookAt(position, target, cameraup) Could someone help me get my camera in the correct position?


XNA Required information to represent 2D Sprite graphically I was thinking about dividing my game engine into 2 threads render thread and update thread (I can't come up on how to divide update thread from physic thread at the moment). That said, I have to duplicate all Sprite informations, what do I really need to represents a 2D Sprite graphically? Here are my ideas (I'll mark with ? things that I'm not sure) Vector2 Position float Rotation ? Vector2 Pivot ? Rectangle TextureRectangle Texture2D Texture Vector2 ImageOrigin ? (is it tracked somewhere else?) If you have any suggestion about using different types for datas, it's appreciated Last part of the question isn't this a lot of data to copy in a buffer?what should I really copy in the buffer?I'm following this tutorial http www.sgtconker.com 2009 11 article multi threading your xna 3 Thanks UPDATE 1 Newer values at the moment Vector2 Position float Rotation Vector2 Pivot Rectangle TextureRectangle Texture2D Texture Color Color byte Facing (can be left or right, I'll do it with an enum) I re read the tutorial, what I was doing wrong is not that I need to pass all those values, I need to pass only changed values as messages. UPDATE 2 Vector2 Position float Rotation Vector2 Pivot Rectangle TextureRectangle Texture2D Texture Color Color bool Flip uint DrawOrder Vector2 Scale bool Visible ? Mhhh, should Visibile be included?


Odd Behaviour XNA Game Component Inside of my main class file I am initializing a number of game components which are used to represent game scenes i.e. main menu and game. I am initilizing each component inside of XNAs LoadContent method without issue and set the default scene as the main menu. I then switch to the game scene. My issue then occurs when I switch back to the main menu scene and then try to start a new game by switch from the menu to the game scene. When I switch from the game to the menu I dispose of the game scene using the GameComponent.Dispose() method provided by the XNA framework. private void UnloadScene(GameScene scene) scene.Dispose() As I have disposed of the game scene I attempt to re initialize the game scene component with the following method. private void LoadScene(GameScene scene) scene new GameScene(this, graphics.GraphicsDevice) Components.Add(scene) I then switch from the menu scene to the game scene using the following method. This method is called in my Update method after the user has selected new game on the main menu. public void SwitchScene(SceneManager manager) sceneManager.HideScene() sceneManager manager manager.ShowScene() This time when the game scene loads I am met with a cornflower blue background and no assets on screen. I have placed a breakpoint within the above method and seen that the game scene is given all of the required data yet nothing is being drawn. However if I explicitly place the following code above the SwitchScene() method after the player has selected new game then the scene is drawn without issue. scene new GameScene(this, graphics.GraphicsDevice) Components.Add(scene) Below is what the code looks like with the second approach mentioned. if (InputHandler.IsHoldingButton(0, Buttons.A, out throwAway)) switch (menuScene.Index) case 0 gameScene new GameScene(this, graphics.GraphicsDevice) Components.Add(gameScene) SwitchScene(gameScene) break case 1 this.Exit() break Is this behaviour intentional, if so how would I attempt to produce the first approach correctly? Below is a screenshot of the graphics device after the second attempt to load the game scene. Note the data in this image is identical to the graphics device when loading the game scene for the first time. Below is the code for the SceneManager class. public class SceneManager DrawableGameComponent private readonly List lt GameComponent gt components public List lt GameComponent gt Components get return components public SceneManager(Game game) base(game) components new List lt GameComponent gt () Indicates whether draw should be called Visible false Indicates whether GameComponent.Update should be called when Game.Update is called Enabled false public virtual void ShowScene() Visible true Enabled true public virtual void HideScene() Visible false Enabled false public override void Update(GameTime gameTime) for (int i 0 i lt components.Count i ) if (components i .Enabled) components i .Update(gameTime) base.Update(gameTime) public override void Draw(GameTime gameTime) for (int i 0 i lt components.Count i ) GameComponent component Components i if ((component is DrawableGameComponent) amp amp ((DrawableGameComponent)component).Visible) ((DrawableGameComponent)component).Draw(gameTime) base.Draw(gameTime)


Collision detection between player and tiles I am trying to implement basic (for now) collision detection into my platformer. I have tiles that are each 16 x 16 in size. The character is 32 x 32 pixels in size and has its own bounding box. Now, in my Tile class, I have a bool, isSolid. Each of these tiles in my array also have a rect for their respective bounding boxes. I am checking to see if there's an intersection between the player and tiles by doing if (player.GetBoundingBox().Intersects(map.tiles (int)player.position.Y 16, (int)player.position.X 16 .bounds) amp amp map.tiles (int)player.position.Y 16, (int)player.position.X 16 .isSolid) ... Now, my problem is that this is extremely inaccurate as I'm rounding off the position. I'm tired as heck right now and for the life of me I can't figure out how to properly do this. What is the best way to approach this issue?


Creating mesh at run time I've a set of voxel data and I want to create a mesh out of it at run time. I've looked into MeshBuilder and MeshHelper but I haven't found anything useful or a good tutorial how to use them. Can anyone tell me how to create a mesh at run time?


Ultimate beginner's tutorial to 3d game dev using XNA Framework? I'm looking for a tutorial that starts at square 1 for game development and moves up through intermediate expert levels of 3D game development. I really want to get into 3D game dev and I've been trying to for awhile in my free time, but I know so little at times that I'm not even sure what terminology to use in order to phrase a question properly. Ideally, I'm hoping to find tutorials for the XNA Framework, what little experience I have is XNA. I've been developing for years and don't really need help with the language. What I know I need help on is stuff like rendering, what exactly a Matrix represents, and other things in the framework's library. I don't even know what all is available in the library.


XNA How does threading work? I would like to implement threading in my XNA game but I'm not sure how things work when compiling for the XBOX 360. Could someone elaborate on this? For example, how many threads does XBOX support? I realize that XNA uses a special version of the Compact Framework. How does this affect the code during development? Do I implement things differently when developing for XBOX than Windows? Thank you.


XNA project won't target .NET 4.0 I am trying to reference the System.Threading.Task assembly. If I am not mistaken, it should be part of mscorlib. But no matter what I do, my project always defaults to the .net 2.0 runtime. Even if I create a brand new XNA 4.0 Windows Phone project, it wants to use the .net 2.0 runtime. Any ideas what I could be missing?


assigning values to shader parameters in the XNA content pipeline I have tried creating a simple content processor that assigns the custom effect I created to models instead of the default BasicEffect. ContentProcessor(DisplayName "Shadow Mapping Model") public class ShadowMappingModelProcessor ModelProcessor protected override MaterialContent ConvertMaterial(MaterialContent material, ContentProcessorContext context) EffectMaterialContent shadowMappingMaterial new EffectMaterialContent() shadowMappingMaterial.Effect new ExternalReference lt EffectContent gt ("Effects MultipassShadowMapping.fx") return context.Convert lt MaterialContent, MaterialContent gt (shadowMappingMaterial, typeof(MaterialProcessor).Name) This works, but when I go to draw a model in a game, the effect has no material properties assigned. How would I go about assigning, say, my DiffuseColor or SpecularColor shader parameter to white or (better) can I assign it to some value specified by the artist in the model? (I think this may have something to do with the OpaqueDataDictionary but I am confused on how to use it the content pipeline has always been a black box to me.)


Why are my 2D positions "off" after adding a camera transformation in XNA? My game's source is on github. I am following this tutorial to create a 2D camera. After I adding the transformation to the SpriteBatch, all of my positions seem to be "off" when I move the ship (and hence camera) away from the screen center. Any idea what might be wrong?


Can I generate collision boxes from a model file with BepuPhysics and XNA? I am currently developing a game using BepuPhysics in XNA 4.0, and I am trying to reasonably match the in game collision Entities with the Model they are associated with. My current workflow involves guessing what size the various segments of the model are, guessing a size and position of a box to match each segment, and throwing stuff at it to see if I'm right. This is not an efficient process. Is there a way to automatically generate the Entity from the Model? If not, is there some other way to speed up my workflow?


3D game special effects, fire, lightning, water, and ice I'm working on a 3d game using OpenGL and would like to take it in a fantasy direction. Specifically I'm thinking of having magic with effects for fire, water, ice, and lightning. My problem is I have no idea how to create these effects. Are there any resources for me on how to learn something like this?


Accept keyboard input when game is not in focus? I want to be able to control the game via keyboard while the game does not have focus... How can I do this in XNA? EDIT I bought a tablet. I want to write a separate app to overly the screen with controls that will send keyboard input to the game. Although, it's not sending the input DIRECT to the game, it's using the method discussed in this SO question https stackoverflow.com questions 6446085 emulate held down key on keyboard To my understanding, my test app is working the way it should be but the game is not responding to this input. I originally thought that Keyboard.GetState() would get the state regardless that the game is not in focus, but that doesn't appear to be the case.


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.


Top Down RPG Movement w Correction? I would hope that we have all played Zelda A Link to the Past, please correct me if I'm wrong, but I want to emulate that kind of 2D, top down character movement with a touch of correction. It has been done in other games, but I feel this reference would be the easiest to relate to. More specifically the kind of movement and correction I'm talking about is Floating movement not restricted to tile based movement like Pokemon and other games where one tap of the movement pad moves you one square in that cardinal direction. This floating movement should be able to achieve diagonal motion. If you're walking West and you come to a wall that is diagonal in a North East South West fashion, you are corrected into a South West movement even if you continue holding left (West) on the controller. This should work for both diagonals correcting in both directions. If you're a few pixels off from walking squarely into a door or hallway, you are corrected into walking through the hall or down the hallway, i.e. bumping into the corner causes you to be pushed into the hall door. I've hunted for efficient ways to achieve this and have had no luck. To be clear I'm talking about the human character's movement, not an NPC's movement. Are their resources available on this kind of movement? Equations or algorithms explained on a wiki or something? I'm using the XNA Framework, is there anything in it to help with this?


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


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


How can I calculate where my camera can be to avoid showing something outside a region? I have a landscape model, which goes from the coordinate 45, 45 to 90, 90. The edge of the model just cuts off and i would like to somehow stop the screen from ever passing these points. Basically sticking a boundary so that you can't see off the side. The game is always in top view, with the camera directly facing down. However the problem is that the player can zoom in and out, obviously you have a wider range of view when zoomed out. (There is a limit to how far you can zoom out, you couldn't zoom out say, so that opposite sides of the map are seen at once). I am assuming using something like Viewport.Project or Unproject, which changes screen coordinates to 3d space and the other way round, could somehow help me in the situation. My initial idea may lag too much, which would be a while loop saying "While projection of screen point.X is less that 45, add 1 to the camera.X" etc. Does anyone have any ideas for this? To sum it up, i need to find a way of stopping anything outside the area of 45, 45 to 90, 90 from being shown on the screen. Thanks for any help!


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


C How to properly play background songs in XNA So I'm using the game states (enum) to change my game screens. I have 2 songs for main menu and game playing states, respectively. To play songs, I'm using an old code example I saw at MSDN, like this bool songStart false Song song1 Song song2 LoadContent method song1 Content.Load lt Song gt (". Songs mainMenuTheme") song2 Content.Load lt Song gt (". Songs mainGameTheme") MediaPlayer.IsRepeating true Update method switch (CurrentGameState) case gameState.mainMenu if (CurrentGameState gameState.mainMenu amp amp !songStart) MediaPlayer.Stop() MediaPlayer.Play(song) songStart true else if (CurrentGameState ! gameState.mainMenu amp amp songStart true) MediaPlayer.Stop() songStart false break case gameState.gamePlaying if (CurrentGameState gameState.gamePlaying amp amp !m SongStart) MediaPlayer.Stop() MediaPlayer.Play(song2) m SongStart true else if (CurrentGameState ! gameState.gamePlaying amp amp songStart true) MediaPlayer.Stop() songStart false break So if I am in mainMenu, the first song plays when I go to gamePalying the first song stops and the second one starts playing. If I return to mainMenu, the mainMenu song plays. My issue however, is that if I click Play game and the state moves to gamePlaying there is no background music! What could've caused the problem? Please help me fix it, I'm stuck for a whole week.


Scripting engine for XNA Say I'm making this big game in C with XNA. What options do I have to include a scripting feature to my code base?


Why would you use a negative value for Bounding Box? I have the following code I'm working with in XNA from the book Professional XNA Programming. It's just pong on a 2d screen plane. We use bounding boxes for collision detection. I'm just having trouble understanding why we would use a negative paddle size for the RedPaddleBox. I read bounding boxes define the minimum and maximum corners of the box, but I'm not sure what that means minimum in terms of coordinate values? If so, why use a negative value when the paddle isn't partly off screen? This is the code line that gave me trouble new Vector3( paddleSize.X 2, in context of BoundingBox leftPaddleBox new BoundingBox( new Vector3( paddleSize.X 2, leftPaddlePosition paddleSize.Y 2, 0), new Vector3( paddleSize.X 2, leftPaddlePosition paddleSize.Y 2, 0)) in the following code Check for collisions with the paddles. Construct bounding boxes to use the intersection helper method. Vector2 ballSize new Vector2( GameBallRect.Width 1024.0f, GameBallRect.Height 768.0f) BoundingBox ballBox new BoundingBox( new Vector3(ballPosition.X ballSize.X 2, ballPosition.Y ballSize.Y 2, 0), new Vector3(ballPosition.X ballSize.X 2, ballPosition.Y ballSize.Y 2, 0)) Vector2 paddleSize new Vector2( GameRedPaddleRect.Width 1024.0f, GameRedPaddleRect.Height 768.0f) BoundingBox leftPaddleBox new BoundingBox( new Vector3( paddleSize.X 2, leftPaddlePosition paddleSize.Y 2, 0), new Vector3( paddleSize.X 2, leftPaddlePosition paddleSize.Y 2, 0)) BoundingBox rightPaddleBox new BoundingBox( new Vector3(1 paddleSize.X 2, rightPaddlePosition paddleSize.Y 2, 0), new Vector3(1 paddleSize.X 2, rightPaddlePosition paddleSize.Y 2,0))


xna Methods for having sprite characters in 3d game? Methods for having sprite characters in 3d game? I am making a game much like Doom. The world is 3d but objects and characters are 2d sprites. I am not asking about billboarding objects. I am asking about methods for having sprite characters that aren't always facing the player and have different frames depending on which way the character is facing. For example when an enemy is walking towards the player it is a 2d texture of a front and when walking away it is a 2d texture of a back. One way I thought I read about was to draw a cube primitive that is "invisible". This 3d cube allows you to track the orientation of the character. Then you apply a sprite frame to each side of the cube but the 2d texture is only drawn on the side the player is looking at. The other way I suspected I could do this is to make a 3d plane in a modeling program and import it to XNA. Then use the billboarding method to make sure the plane is always facing the player (you don't see the edge). Apply a the appropriate 2d texture (sprite frame) to the plane based on the direction the character is facing. I know this is not how Doom did it but please tell me what you think of my ideas or a method on how this can be done. Thank you.


Real Time vs Turn Based (XNA) What is a more difficult type of game to develop on XNA A Real Time multiplayer game or a Turn Based multiplayer game? (not client server or peer to peer, just in general) Any links to articles would be greatly appreciated!


Simple 2d tile based lighting in xna I am currently trying to implement simple lighting into my game. My world is represented in a 2d array of numbers, each number being a certain tile. I am changing the color parameter in the spritebatch.Draw method to dim the tiles, and that is working quite well for me(I don't know how to use shaders).Each tile can have a light level from 0 to 5, and depending on its level it will be brighter darker. The problem I have is that I used this code to simulate lighting public void Update() foreach (NonCollisionTiles tile in nonCollisionTiles) foreach (NonCollisionTiles otherTile in nonCollisionTiles) if (otherTile.Rectangle.X tile.Rectangle.X amp amp (otherTile.Rectangle.Y size tile.Rectangle.Y 1 otherTile.Rectangle.Y size tile.Rectangle.Y 1)) if (tile.Light lt otherTile.Light) tile.Light otherTile.Light 1 else if (otherTile.Rectangle.X size tile.Rectangle.Y amp amp (otherTile.Rectangle.X size tile.Rectangle.X 1 otherTile.Rectangle.Y size tile.Rectangle.X 1)) if (tile.Light lt otherTile.Light) tile.Light otherTile.Light 1 But I'm not sure if it works or not and it lowers my FPS to 1. I have no idea as to how I can implement my lighting system. Essentially, I want it to look like a torch in Minecraft, but in 2d. Here is the code for my tiles using System using System.Collections.Generic using System.Linq using System.Text using Microsoft.Xna.Framework.Graphics using Microsoft.Xna.Framework using Microsoft.Xna.Framework.Content namespace Tile Map class Tiles protected Texture2D texture protected int light 1 public int Light get return light set light value protected Color color private Rectangle rectangle public Rectangle Rectangle get return rectangle protected set rectangle value private static ContentManager content public static ContentManager Content protected get return content set content value public void Update() color new Color(light 51,light 51,light 51) public void Draw(SpriteBatch spriteBatch) spriteBatch.Draw(texture, rectangle, null, color, 0, Vector2.Zero,SpriteEffects.None,0f) class CollisionTiles Tiles public CollisionTiles(int i, Rectangle newRectangle) texture Content.Load lt Texture2D gt ( "Images Tile" i) this.Rectangle newRectangle class NonCollisionTiles Tiles public NonCollisionTiles(int i, Rectangle newRectangle) texture Content.Load lt Texture2D gt ( "Images Tile" i) this.Rectangle newRectangle This is what I am trying to do Any help is appreciated!


Using a Vertex Buffer and DrawUserIndexedPrimitives? Let's say I have a large but static world and only a single moving object on said world. To increase performance I wish to use a vertex and index buffer for the static part of the world. I set them up and they work fine however if I throw in another draw call to DrawUserIndexedPrimitives (to draw my one single moving object) after the call to DrawIndexedPrimitives, it will error out saying a valid vertex buffer must be set. I can only assume the DrawUserIndexedPrimitive call destroyed replaced the vertex buffer I set. In order to get around this I must call device.SetVertexBuffer(vertexBuffer) every frame. Something tells me that isn't correct as that kind of defeats the point of a buffer? To shed some light, the large vertex buffer is the final merged mesh of many repeated cubes (think Minecraft) which I manually create to reduce the amount of vertices indexes needed (for example two connected cubes become one cuboid, the connecting faces are cut out), and also the amount of matrix translations (as it would suck to do one per cube). The moving objects would be other items in the world which are dynamic and not fixed to the block grid, so things like the NPCs who move constantly. How do I go about handling the large static world but also allowing objects to freely move about?


SpriteSheet Animation with XNA Hi i'm working on my First 2D Game with XNA and I have a little problem. To give a running effect to my Sprite, I scroll through a SpriteSheet with this code(running right) if (AnimationDelay 6) if (CurrentFrameR.X lt SheetSizeR.X) CurrentFrameR.X else CurrentFrameR.Y CurrentFrameR.X 1 if (CurrentFrameR.Y gt SheetSizeR.Y) CurrentFrameR.X 0 CurrentFrameR.Y 0 AnimationDelay 0 else AnimationDelay 1 xPosition xDeplacement And these are the objects used Point FrameSizeR new Point(29, 33) Point SheetSizeR new Point(5, 1) Point CurrentFrameR new Point(0, 0) int AnimationDelay 0 I have the same Code with different SpriteSheet when the sprite is running Left. Everything is working fine I'd say 90 of the time but the other 10 the sprite animation stays on one Frame of the SpriteSheet, on both directions(left and right) and it stays stuck until I close the program. The thing is I can't quite figure out why since it never happens at the same moment..Sometimes after 10,15,30 seconds and sometimes even on boot! Any idea why? Thanks in advance and let me know if you need any other parts of the code


Line segment circle intersection X value seems wrong? Major Edit I'm making a Breakout clone, and having difficulty with collision detection between a circle and line segment. Apologies, my earlier question was a result of frustration and no sleep ) Having read this post on collision detection I've re written my collision code to the following Takes 2 points on a line, a circle centre, and a circle radius Returns true is collision, false otherwise public Boolean DoesCollide(Vector2 a, Vector2 b, Vector2 c, float rad) First up, let's normalise our vectors so the circle is on the origin Vector2 normA a c Vector2 normB b c Vector2 d normB normA Want to solve as a quadratic equation, need 'a','b','c' components float aa Vector2.Dot(d, d) float bb 2 (Vector2.Dot(normA, d)) float cc Vector2.Dot(normA,normA) (rad rad) Get determinant to see if LINE intersects double deter Math.Pow(bb, 2.0) 4 aa cc if (deter gt 0) Get t values (solve equation) to see if LINE SEGMENT intersects double t ( bb Math.Sqrt(deter)) (2 aa) double t2 ( bb Math.Sqrt(deter)) (2 aa) Boolean match false if (0.0 lt t amp amp t lt 1.0) Interpolate to get collision point Vector2 collisionPoint c Vector2.Lerp(normA, normB, (float)t) match true if (0.0 lt t2 amp amp t2 lt 1.0) Vector2 collisionPoint2 c Vector2.Lerp(normA, normB, (float)t2) match true return match else return false However, I'm getting strange results for the X components of the collision points found 'on hit' see the following debug output Coll at X 1033.931 Y 620 , t1 0.203759334390812, Normalised X 0.8576241 Y 0.5142772 Coll2 at X 1052.069 Y 620 , t2 0.409877029245551, Normalised X 0.8615275 Y 0.5077109 Circ cent X 1043 Y 610 , rad 13.5 As you can see, the X components are 10px either side of the circle centre, but the Y component (620) is the very topmost pixel of the top of the Breakout paddle. Surely here the X points can't be 20 pixels apart, given the location of the Y point?


Rendering fancy particles? I'm making a tower defense game for Windows (not phone) in XNA. I've seen this video of another tower defense game for Windows Phone that uses particle effects, which I really like. They change color, glow and density as they move away from the explosion. Really cool stuff! http www.youtube.com watch?v YhPr4A4LRPQ amp hd 1 I would like a similar result (particle wise) to the stuff in the video, however, I don't know where to start. I suppose I need to do linelist hardware instancing to achieve the result, and then update every particle position on the CPU. Or is there a better alternative? Post your suggestions. That'd be great, thanks. Edit It's the explosion particle effect that I want to implement. Not the particle effects that the projectiles leave when they fire.


XNA SpriteBatch.Draw with rotation, scaling and origin? I use a 1x1 pixel 2d texture as source for SpriteBatch.Draw. The texture is scaled and rotated around an origin. The left image is only scaling. The right one scaling rotation around the origin at the bottom center. I need the right image as result. i.e. scaled to 5x10 and rotated around 2.5x10 The problem is with the 1x1 texture the draw starts to act strange if the origin parameter is outside the source texture. And as long as the origin is limited to a max of 1x1 its not possible to rotate around the bottom center of the scaled texture. Why does the origin behave strangely if it is outside the source texture? With strange I mean the texture moves much more then the origin value set. i.e. if its origin x 10 the texture moves much more then 10 pixels.


snapping an angle to the closest cardinal direction I'm developing a 2D sprite based game, and I'm finding that I'm having trouble with making the sprites rotate correctly. In a nutshell, I've got spritesheets for each of 5 directions (the other 3 come from just flipping the sprite horizontally), and I need to clamp the velocity rotation of the sprite to one of those directions. My sprite class has a pre computed list of radians corresponding to the cardinal directions like this protected readonly List lt float gt CardinalDirections new List lt float gt MathHelper.PiOver4, MathHelper.PiOver2, MathHelper.PiOver2 MathHelper.PiOver4, MathHelper.Pi, MathHelper.PiOver4, MathHelper.PiOver2, MathHelper.PiOver2 MathHelper.PiOver4, MathHelper.Pi, Here's the positional update code if (velocity Vector2.Zero) return var rot ((float)Math.Atan2(velocity.Y, velocity.X)) TurretRotation SnapPositionToGrid(rot) var snappedX (float)Math.Cos(TurretRotation) var snappedY (float)Math.Sin(TurretRotation) var rotVector new Vector2(snappedX, snappedY) velocity rotVector ...snip private float SnapPositionToGrid(float rotationToSnap) if (rotationToSnap 0) return 0.0f var targetRotation CardinalDirections.First(x gt (x rotationToSnap gt 0.01 amp amp x rotationToSnap lt 0.01)) return (float)Math.Round(targetRotation, 3) What am I doing wrong here? I know that the SnapPositionToGrid method is far from what it needs to be the .First(..) call is on purpose so that it throws on no match, but I have no idea how I would go about accomplishing this, and unfortunately, Google hasn't helped too much either. Am I thinking about this the wrong way, or is the answer staring at me in the face? EDIT Thanks Gregory for the answer. Only thing I really had to modify from the answer was to re construct the velocity vector to the new snapped rotation (I'm sure there are further optimizations that I can do, but for now it's enough that it works!) var snappedX (float)Math.Round(Math.Cos(TurretRotation), 3) velocity.Length() var snappedY (float)Math.Round(Math.Sin(TurretRotation), 3) velocity.Length() var rotVector new Vector2(snappedX, snappedY) FOLLOW UP EDIT The initial answer worked very well as a naive implementation, but suffered from inaccuracies of up to 45 degrees when dealing with negative angles 3.14 snapped to 2.356 for instance. To correct that, I added a check to account for those situations. Below is a complete implementation of a SnapToGrid method. Some optimizations have been made, like pre computing the various divisors of Pi to avoid the division. Further optimization could possibly be achieved by looking for short circuit scenarios, i.e. if rotationToSnap 0, but if anyone has further optimizations, I'd be curious to see them! public static float SnapPositionToGrid(float rotationToSnap) if (rotationToSnap 0) return 0.0f var modRot rotationToSnap MathHelper.PiOver4 float finalRot if (modRot lt RoundedPiOver8) if (modRot lt RoundedPiOver8) finalRot rotationToSnap MathHelper.PiOver4 modRot else finalRot rotationToSnap modRot else finalRot rotationToSnap MathHelper.PiOver4 modRot return (float)Math.Round(finalRot, 3)


Sprite and Physics components or sub components? I'm taking my first dive into creating a very simple entity framework. The key concepts (classes) are Entity (has 0 components, can return components by type) SpriteEntity (everything you need to draw on screen, including lighting info) PhysicsEntity (velocity, acceleration, collision detection) I started out with physics notions in my sprite component, and then later removed them to a sub component. The separation of concerns makes sense a sprite is enough information to draw anything (X, Y, width, height, lighting, etc.) and physics piggybacks (uses the parent sprite to get X Y W H) while adding physics notions of velocity and collisions. The problem is that I would like collisions to be on an entity level meaning "no matter what your representation is (be it sprites, text, or something else), collide against this entity." So I refactored and redirected collision handling from entities to sprite.physics, while mapping and returning the right entity on physics collisions. The problem is that writing code like this.GetComponent lt SpriteComponent gt ().physics is a violation of abstraction. Which made me think (this is the TLDR) should I keep physics as a separate component from sprites, or a sub component, or something else? How should I share data and separate concerns?


How to clip textures when drawing? How do i draw a texture2D in a specific area (rectangle) where the texture is bigger than the rectangle, and i dont want to draw outside the rectangle. So that means i want to cut the texture so it fits the rectangle area (if its too big). For example if the rectangle area is 200 x 100 and my texture (the smiley) is 200 x 150 then i want to cut the last 50 off so it only draws 200 x 100


Anyone can suggest some Game Frameworks for GNU Linux? So I've been developing a little bit with XNA C in Windows, not really much just some 2D stuff, but I've found that XNA is a really good framework. I'm a GNU Linux user, and I'm definitely migrating my desktop to Gentoo Linux (I've been using Arch in my laptop for a while now). But, of course, I need a C XNA alternative... I'm not really an expert in any language, so I can really pick up anything (except, maybe, Functional ones), I prefer C Like languages like Java or Ruby, I tried Python but found the Whitespace syntax confusing. I would like to hear some of you'r suggestions, I'm not asking for "the best", but for "some suggestions", so I think this is objective enough. Probably you're going to suggest C SDL, but I would prefer something more "High Level" like XNA, but I'm open to discuss anything. So... any ideas ? Note I think this questions meets the guidelines for this site, if it doesn't please not only downvote this question, but comment on what can I do to improve it. Thanks. PS 2D Games, not 3D


BasicEffect and SkinnedEffect treating WorldViewProj differently? I made a ModelBatch class that batches and draw rigged unanimated and skinned animated models. For now, BasicEffect is assigned to rigged models (XNA Model Processor) and SkinnedEffect is assigned to skinned models (Based on Microsoft's Skinned Model Sample). The problem occurs when setting the shaders parameters. In the RenderBatch() method, I wrote ... foreach (Effect effect in mesh.Effects) if (effect is BasicEffect) if it's a rigged model. effect.Parameters "WorldViewProj" .SetValue(modelInfo.world viewProjection) else it's a skinned model. effect.Parameters "WorldViewProj" .SetValue(viewProjection) effect.Parameters "Bones" .SetValue(modelInfo.boneTransforms) ... When running the game, the rigged model's position is locked to the camera position for the first few frames. Afterwards, everything works perfectly (the rigged model position's is correct). The skinned model doesn't have that position displacement problem at runtime even if I only set the "WorldViewProj" parameter (so it's not because of the "Bones" parameter). In order to work perfectly, I had to changed the rigged model part to if (effect is BasicEffect) if it's a rigged model. BasicEffect basicEffect effect as BasicEffect basicEffect.World modelInfo.world basicEffect.View this.camera.View basicEffect.Projection this.camera.Projection This way, the rigged model is instantly placed at the right place, but I don't like it. Also, what is really stange is that if I do not set any view or projection for the rigged model, like this if (effect is BasicEffect) if it's a rigged model. do nothing. I will still see the rigged model locked to the camera's position. Anyone knows why setting "WorldViewProj" parameter of a SkinnedEffect works perfectly, but not for a BasicEffect? I hope there's enough informations and thank you for answering! EDIT ANSWERED I found the source of the problem. The scale and rotation of the rigged model were changed in the content processor options, so the model was modified at runtime. I changed those options back to their default values and set the rotation and scale in the code instead (Matrix.CreateScale and Matrix.CreateRotationX) and the model was at the right place. Hence, I think that changing the model world information at runtime created the displacement lag.


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.


Bug in XNA Developer function CalculateEigenVector() from the file "xnacollision.cpp"? I am trying to decipher the content of the Microsoft XNA Developer source file "xnacollision.cpp" and I've found a function that calculates one of the three eigenvectors of a homogeneous system of three linear equations. The name of that function is CalculateEigenVector() and its content is as follows static inline XMVECTOR CalculateEigenVector( FLOAT m11, FLOAT m12, FLOAT m13, FLOAT m22, FLOAT m23, FLOAT m33, FLOAT e ) FLOAT f1, f2, f3 FLOAT fTmp 3 fTmp 0 ( FLOAT )( m12 m23 m13 ( m22 e ) ) fTmp 1 ( FLOAT )( m13 m12 m23 ( m11 e ) ) fTmp 2 ( FLOAT )( ( m11 e ) ( m22 e ) m12 m12 ) XMVECTOR vTmp XMLoadFloat3( (XMFLOAT3 )fTmp ) if( XMVector3Equal( vTmp, XMVectorZero() ) ) planar or linear we only have one equation find a valid one if( ( m11 e ! 0.0 ) ( m12 ! 0.0 ) ( m13 ! 0.0 ) ) f1 m11 e f2 m12 f3 m13 else if( ( m12 ! 0.0 ) ( m22 e ! 0.0 ) ( m23 ! 0.0 ) ) f1 m12 f2 m22 e f3 m23 else if( ( m13 ! 0.0 ) ( m23 ! 0.0 ) ( m33 e ! 0.0 ) ) f1 m13 f2 m23 f3 m33 e else error, we'll just make something up we have NO context f1 1.0 f2 0.0 f3 0.0 if( f1 0.0 ) vTmp XMVectorSetX( vTmp, 0.0f ) else vTmp XMVectorSetX( vTmp, 1.0f ) if( f2 0.0 ) vTmp XMVectorSetY( vTmp, 0.0f ) else vTmp XMVectorSetY( vTmp, 1.0f ) if( f3 0.0 ) vTmp XMVectorSetZ( vTmp, 0.0f ) recalculate y to make equation work if( m12 ! 0.0 ) vTmp XMVectorSetY( vTmp, ( FLOAT )( f1 f2 ) ) else vTmp XMVectorSetZ( vTmp, ( FLOAT )( ( f2 f1 ) f3 ) ) if( XMVectorGetX( XMVector3LengthSq( vTmp ) ) gt 1e 5f ) return XMVector3Normalize( vTmp ) else Multiply by a value large enough to make the vector non zero. vTmp 1e5f return XMVector3Normalize( vTmp ) In my opinion there are two mistakes 1) The code snippet recalculate y to make equation work if( m12 ! 0.0 ) vTmp XMVectorSetY( vTmp, ( FLOAT )( f1 f2 ) ) should be changed with if( f1 ! 0.0f ) vTmp XMVectorSetX( vTmp, ( FLOAT )( f2 f1 ) ) if( f2 ! 0.0f ) vTmp XMVectorSetY( vTmp, ( FLOAT )( f1 f2 ) ) 2) In the next else block instead vTmp XMVectorSetZ( vTmp, ( FLOAT )( ( f2 f1 ) f3 ) ) we must have vTmp XMVectorSetZ( vTmp, ( FLOAT )( ( f2 f1 ) f3 ) ) Please tell me if I am wrong or right!


Using XNA ContentPipeline to export a file in a machine without full XNA GS My game uses the Content Pipeline to load the spriteSheet at runtime. The artist for the game sends me the modified spritesheet and I do a build in my machine and send him an updated project. So I'm looking for a way to generate the xnb files in his machine (this is the output of the content pipeline) without him having to install the full XNA Game studio. I don't want my artist to install VS Xna (I know there is a free version of VS but this won't scale once we add more people to the team). I'm not interested in running this editor tool in Xbox so a Windows only solution works. I'm aware of MSBuild options but they require full XNA I researched Shawn's blog and found the option of using Msbuild Sample or a new option in XNA 4.0 that looked promising here but seems like it has the same restriction Need to install full XNA GS because the ContentPipeline is not part of the XNA redist. So has anyone found a workaround for this?


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


Trying to use stencils in 2D while retaining layer depth This is a screen of what's going on just so you can get a frame of reference. The problem I'm running into is that my game is slowing down due to the amount of texture swapping I'm doing during my draw call. Since walls, characters, floors, and all objects are on their respective sprite sheet containing those types, per tile draw, the loaded texture is swapping no less than 3 to 5 times as it cycles and draws the sprites in order to layer properly. Now, I've tried throwing all common objects together into their respective lists, and then using layerDepth drawing them that way which makes things a lot better, but the new problem I'm running into has to do with the way my doors windows are drawn on walls. Namely, I was using stencils to clear out a block on the walls that are drawn in the shape of the door window so that when the wall would draw, it would have a door window sized hole in it. This is the way my draw was set up for walls when I was going tile by tile rather than grouped up common objects. first it would check to see if a door window was on this wall. If not, it'd skip all the steps and just draw normally. Otherwise end the current spriteBatch Clear the buffers with a transparent color to preserve what was already drawn start a new spritebatch with stencil settings draw the door area end the spriteBatch start a new spritebatch that takes into account the previously set stencil draw the wall which will now be drawn with a hole in it end that spritebatch start a new spritebatch with the normal settings to continue drawing tiles In the tile by tile draw, clearing the depth stencil buffers didn't matter since I wasn't using any layerDepth to organize what draws on top of what. Now that I'm drawing from lists of common objects rather than tile by tile, it has sped up my draw call considerably but I can't seem to figure out a way to keep the stencil system to mask out the area a door or window will be drawn into a wall. The root of the problem is that when I end a spriteBatch to change the DepthStencilState, it flattens the current RenderTarget and there is no longer any depth sorting for anything drawn further down the line. This means walls always get drawn on top of everything regardless of depth or positioning in the game world and even on top of each other as the stencil has to happen once for every wall that has a door or window. Does anyone know of a way to get around this? To boil it down, I need a way to draw having things sorted by layer depth while also being able to stencil mask out portions of specific sprites.


How can I get a 2D texture to rotate like a compass in XNA? I'm working on a small maze puzzle game and I'm trying to add a compass to make it somewhat easier for the player to find their way around the maze. The problem is I'm using XNA's draw method to rotate the arrow and I don't really know how to get it to rotate properly. What I need it to do is point towards the exit from the player's position, but I'm not sure how I can do that. So does anyone know how I can do this? Is there a better way to do it?


How do I modify a Boids algorithm to be player controlled? Found source code on Boids in C . http 3carrotsonastick.wordpress.com 2012 11 01 boids in c xna How do I go about making the raven class in the above player controlled? If I could control it myself, it would be a great help, but I don't know how to go about it.


How do I get the mouse position relative to the window, not the whole screen? I am developing an XNA game. I run it in window mode. I need to handle mouse events, but when I use the Mouse class from Xna.Framework.Input.Mouse, I get the the mouse position on the whole screen. I use this code MouseState state Mouse.getState() Point position new Point(state.X,state.Y) Rectangle hitbox new Rectangle(180, 410, 14, 14) if (area.Contains(mousePosition)) fire event How do I detect the mouse position within the current game window?


How to make a registration for my game? Me and my (new) company want to sell a very simple game, but we want it so that only the person that buys it can play it. I want to know if it's possible to make a "registration" window pop up when the game either first starts or when it is being installed (still haven't decided whether or not to use an installer or not). It would require the person to input a registration key and it would then check that key against a database to 1. check to see if it's actually there and 2. to see if it has not been used already. If both are true, it lets you install or play the game an infinite number of times on that computer up until it is uninstalled. Is this possible in the c xna code, or would i have to use some advanced form of executable programming?


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.


Sound Effects on Monogame delay I have recently added some Sound Effects to my game, but the problem that I am dealing with now, is that they have for a half of second delay, or more sometimes. Also, if I press repeatedly on that button, the sound effect does not play each time that I press on the button, and when I finish pressing, it plays at least once (I think from the previous presses). How can I fix this problem? Here is my Play function, if it will help with something ... public void Play(SFX effect) if(!Muted) switch(effect) case SFX.ButtonTap tapSfx Instance.Play() break case SFX.Hit hitSfx Instance.Play() break case SFX.Die dieSfx Instance.Play() break Thanks.


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


XNA Per Polygon Collision Check I'm working on a project in XNA for WP7 with a low poly environment, my problem is I need to setup a working per polygon collision check between 2 or more 3d meshes. I've checked tons of tutorials but all of them use bounding boxes, bounding spheres,rays etc., but what I really need is a VERY precise way of checking if the polygons of two distinct models have intersected or not. If you could redirect me to an example or at least give me some pointers I would be grateful.


Problem building a color grading map I am trying to build a default color grading map into a 1024x32 RenderTarget. Here is my shader code VertexShaderOutput VertexShaderFunction(VertexShaderInput input) VertexShaderOutput output output.Position float4(input.Position,1) output.TexCoord input.TexCoord return output float4 PixelShaderFunction(float2 TexCoord TEXCOORD0) COLOR0 float temp TexCoord.r 1024 float4 result (float4)0 result.a 1 result.r (temp 32) 32 result.g TexCoord.g result.b TexCoord.r return result I'm using Catalin Zima's quad renderer to render the color grading map AND to render the contents of the texture back onto the screen. Here is the copy shader texture Texture sampler targetSampler sampler state Texture (Texture) AddressU CLAMP AddressV CLAMP MagFilter POINT MinFilter POINT Mipfilter POINT VertexShaderOutput VertexShaderFunction(VertexShaderInput input) VertexShaderOutput output output.Position float4(input.Position,1) output.TexCoord input.TexCoord halfPixel return output float4 PixelShaderFunction(float2 TexCoord TEXCOORD0) COLOR0 return tex2D(targetSampler, TexCoord) When I take the resulting image into the Photoshop, the bottom right pixel of the texture always equals (247, 247, 255), even though top left color equals zero. What could be the problem? I checked the quad renderer class it is recording texture coordinates exactly 0,1 into the quad's corners. I am aligning pixels to texels with the halfPixel and using point texture sampling. Somewhy the V component of texture coordinates never reaches one. I have no clue where the problem can be. As I plan to use this texture for color grading, the accuracy is crucial. UPDATE So far I can only achieve the needed result with the folowing shader code float4 PixelShaderFunction(float2 TexCoord TEXCOORD0) COLOR0 float temp TexCoord.r 1024 float4 result (float4)0 result.a 1 float m (temp 32) result.r m 32 0.035f m 32 result.g TexCoord.g 0.035f TexCoord.g result.b TexCoord.r return result Which is very wierd. UPDATE 2 Ok, I had to modulo divide over 33 instead of 32, but I still have to correct the V coordinate. float4 PixelShaderFunction(float2 TexCoord TEXCOORD0) COLOR0 float temp TexCoord.r 1024 float4 result (float4)0 result.a 1 float m (temp 33) result.r m 33 0.035f m 33 result.g TexCoord.g 0.035f TexCoord.g result.b TexCoord.r return result


Shadow map depth error makes all light be covered and hidden I've been following the tutorials listed below http www.riemers.net eng Tutorials XNA Csharp Series3 Shadow map.php http xbox.create.msdn.com en US education catalog sample shadow mapping 1 And I made my shadow map creator effect float4x4 WorldViewProjection float4x4 LightingWorld float4x4 LightingViewProjection struct VertexToPixel float4 Position POSITION float Depth TEXCOORD0 VertexToPixel ShadowMapVertexShader(float4 position POSITION) VertexToPixel output (VertexToPixel)0 output.Position mul(position, mul(LightingWorld, LightingViewProjection)) output.Depth output.Position.z output.Position.w return output float4 ShadowMapPixelShader(VertexToPixel input) COLOR0 float4 color input.Depth color.a 1 return color I use the following flashlight (which has a cone angle coneAngleHalfRad 2) View and Projection matrices for the shadow map (and for checking the depths later) lightProjection Matrix.CreatePerspectiveFieldOfView( coneAngleHalfRad 2, 1, 1, 0.25f, range) Helper.Message(this, "draw shadow maps " needsShadows) Helper.Message(this, "rotation up " rotation.Up) lightView Matrix.CreateLookAt(position, position (direction range), rotation.Up) lightViewProjection lightView lightProjection DepthMapMakerEffect.Parameters "LightingWorld" .SetValue(Matrix.Identity) DepthMapMakerEffect.Parameters "LightingViewProjection" .SetValue(lightViewProjection) DepthMapMakerEffect.Techniques 0 .Passes 0 .Apply() device.SetRenderTarget(RenderDirectional) device.Clear(ClearOptions.Target ClearOptions.DepthBuffer, Color.Black, 1.0f, 0) drawAction(this, DepthMapMakerEffect) device.SetRenderTarget(null) ShadowMapDirectional (Texture2D)RenderDirectional I set my shadow map to the effect TextureManager.DynamicTexturingEffect.Parameters "Flashlight" numFlashlightsPP "Map" .SetValue(((Flashlight)lights lightIndex ).ShadowMapDirectional) And when I am drawing the light with additive blend state, I use the following code to get the depths from the shadow map and from the camera (is it from the camera? I didn't understand yet) shared float DepthBias 0.001f ... shared Texture Flashlight0Map shared sampler Flashlight0MapSampler sampler state texture lt Flashlight0Map gt magfilter LINEAR minfilter LINEAR mipfilter LINEAR AddressU clamp AddressV clamp ... Find the position of this pixel in light space. float4 lightingPosition mul(worldPosition, flashlight.LightingViewProjection) Find the position in the shadow map for this pixel. float2 shadowTexCoord 0.5 lightingPosition.xy lightingPosition.w float2(0.5, 0.5) shadowTexCoord.y 1.0f shadowTexCoord.y Get the current depth stored in the shadow map. float shadowDepth tex2D(Flashlight0MapSampler, shadowTexCoord).r Calculate the current pixel depth. The bias is used to prevent folating point errors that occur when the pixel of the occluder is being drawn. float ourDepth (lightingPosition.z lightingPosition.w) DepthBias ... float intensity 0 if (ourDepth lt shadowDepth) if (atten gt 0) intensity saturate((flashlight.Range dist) flashlight.Range) (dot(vertexNormal, perVertexNormal) fog) atten But what happens is that the result is ALWAYS "ourDepth shadowDepth", which makes the entire light always hidden so it's always shadowed no matter if there's an object in front of it or not. What could I possible be doing wrong? I think I used wrong values in the flashlight's View and Projection. But I can't find the error. What might be the problem? Any suggestion may help! EDIT I'm not using the same aspect ratio of the screen and of the camera for the shadow map. Do I need to?


How to use images text etc. in XNA without Content Pipeline? I'm currently writing a program in C with the XNA framework. It is absolutely necessary for the game's images and text assets to be visible by the end user in the form of PNG files, so I can't use the content pipeline. How would I go about using graphics and text in my XNA game without it?


XNA Sprite mouse selection with layered overlapping sprites If I use mouse coordinates to select a sprite does XNA provide a built in way to return the top most sprite on the screen at a coordinate? I am trying to highlight the selected sprite, but when iterating through my sprites at the specific mouse location there can be multiple sprites found. The way my game works any one of the sprites found is valid to be on top.


What is the value of gameTime.ElapsedGameTime.TotalSeconds? I was wondering what is exactly the value of gameTime.ElapsedGameTime.TotalSeconds in a second? Please explain it to me completely and as great as you can.


Are concurrent Update and Draw calls possible in XNA? I am making a real time game in XNA and I would like to reduce the Update() call frequency while getting as many Draw() calls as possible. This would enable the program to finish long calculations in the Update() method while Draw() is still regularly called to perform interpolation and rendering to have the game appear running smoothly. But, it seems like Draw() is never invoked before Update() has finished. This creates stuttering. Is it possible to achieve concurrent calls to Draw() before Update() has finished?


Xna How do you use large animations for a menu In the main menu of my game I have several animations that pause in specific frames. I made the sprite sheets for the different layers, but then I found out that the sprite sheet has to be smaller than 2048 pixels. My sprite sheet is 14400 pixels with 18 frames... How can I play these large animations? I tried video playback but I couldn't find a way to do this...


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


Ball Physics Bounce height altered by elasticity of ball and bounce surface I have created a bouncing ball simulator using XNA and I am happy with my use of gravity, acceleration, change of direction and friction spin. However, I am now at a stage where I would like to define my ball as being made of a different material, subsequently meaning that the "bounce height" will be different depending on the elasticity of the material. Ultimately, I will also want differing types of bounce surfaces as well. This will mean that I could have bounces as varied as Rubber ball on concrete. Ping pong ball on wood. Concrete ball on mud. Etc., etc. My question is How should I alter my bounce height depending on the material(s)? I have found some information about Young's Modulus of Elasticity but I would be grateful if someone could advise as to how I use this (or another) value as a ratio in my "bounce" calculation. Thanks in advance and please let me know if you would like to know anything else.