_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
12 | Generating island terrains with Simplex Noise (C XNA) I've got one little question Is there any code or sample which shows how the simplex noise works? I cannot find anything about it... How should I implement it, without the knowledge how the algorithm works?... The other question is Is the simplex noise a good algorithm for island generation? I need huge islands (really huge), with different layers (sand, gras, stone) and clearly visible height differences, which have soft edges, so you can go out into water without jumping over uneven surfaces. |
12 | How do I enable higher FPS in XNA 4.0? I created a FpsCounter DrawableGameComponent (linked to code, it's longish). It works great It displays 60.0 fps normally. If I artificially slow down the game loop, it drops. My 'game' at the moment is a single keyboard controlled sprite, so it should be possible to render more frequently than 60 frames a second. I figured turning off vertical synchronization would increase the FPS cap public Game1() graphics new GraphicsDeviceManager(this) PreferredBackBufferWidth WindowWidth, PreferredBackBufferHeight WindowHeight, SynchronizeWithVerticalRetrace false, graphics.ApplyChanges() Content.RootDirectory "Content" However, even though the above code seems like it should turn off vsync, it doesn't seem to be. Is there something wrong with my constructor, or perhaps my FPS calculations? Or is there something else that may be limiting the frame count? |
12 | Monogame Android Using content from PCL I'm quite new to Monogame and PCL, but I hope someone can help me with my question. I have a Monogame Android project with references a PCL which targets .NET 4.5, iOS and Android. The PCL has content files suchs as SpriteFont and Texture2D. They are set to "Content", "Always copy" and are .xnb files. The problem is when I start my Android game I get a "asset not found" exception for the content in the PCL. When I launch my Windows game it works all fine. To begin with, can I have content files in a PCL and is that good practice? |
12 | How to draw only visible models of the game? Suppose I have an array of models, each having it s own position in the world space (scale translation matrix). And I have an orthogonal camera. How can I test if model is visible , i.e. is in the range of the camera? Like this xxxxxxxx xxxxxxxxxxxxxx xxxxxxxxx I want to know whether x is in a frame or not. Thank you very much in advance, I know it should be a fairly simple (if not trivial) task ) |
12 | What is going on in this SAT vector projection code? I'm looking at the example XNA SAT collision code presented here http www.xnadevelopment.com tutorials rotatedrectanglecollisions rotatedrectanglecollisions.shtml See the following code private int GenerateScalar(Vector2 theRectangleCorner, Vector2 theAxis) Using the formula for Vector projection. Take the corner being passed in and project it onto the given Axis float aNumerator (theRectangleCorner.X theAxis.X) (theRectangleCorner.Y theAxis.Y) float aDenominator (theAxis.X theAxis.X) (theAxis.Y theAxis.Y) float aDivisionResult aNumerator aDenominator Vector2 aCornerProjected new Vector2(aDivisionResult theAxis.X, aDivisionResult theAxis.Y) Now that we have our projected Vector, calculate a scalar of that projection that can be used to more easily do comparisons float aScalar (theAxis.X aCornerProjected.X) (theAxis.Y aCornerProjected.Y) return (int)aScalar I think the problems I'm having with this come mostly from translating physics concepts into data structures. For example, earlier in the code there is a calculation of the axes to be used, and these are stored as Vector2, and they are found by subtracting one point from another, however these points are also stored as Vector2s. So are the axes being stored as slopes in a single Vector2? Next, what exactly does the Vector2 produced by the vector projection code represent? That is, I know it represents the projected vector, but as it pertains to a Vector2, what does this represent? A point on a line? Finally, what does the scalar at the end actually represent? It's fine to tell me that you're getting a scalar value of the projected vector, but none of the information I can find online seems to tell me about a scalar of a vector as it's used in this context. I don't see angles or magnitudes with these vectors so I'm a little disoriented when it comes to thinking in terms of physics. If this final scalar calculation is just a dot product, how is that directly applicable to SAT from here on? Is this what I use to calculate maximum minimum values for overlap? I guess I'm just having trouble figuring out exactly what the dot product is representing in this particular context. Clearly I'm not quite up to date on my elementary physics, but any explanations would be greatly appreciated. |
12 | How can I seamlessly loop a background texture in XNA? Using XNA, I made a looping background with several textures (whose widths are over 1024px). There are fewer than five of them. All the pictures are different, held in a list and their positions are looped. When it reaches the end of the loop, it flickers. In my Update method I do this dt (float)gameTime.ElapsedTime.TotalSeconds foreach(BackGroundObject bgo in myList) bgo.Position speed dt So that it works based on gameTime. Then, in my drawing function is this code foreach(BackGroundObject bgo in myList) spriteBatch.Draw(bgo.Picture, bo.Position, Color.White) Here is the BackGroundObject class. The game holds a list of BackGroundObjects and Update changes their positions. If any object goes off screen, its position is set again a BackGroundObject is loaded once and the game always uses same BackGroundObjects. MayDraw is a property of the picture's position. I.e. If in the screen or not. public class BackGroundObject public Texture2D Picture public Vector2 Position, DrawPosition public bool MayDraw public BackGroundObject(Vector2 position, Texture2D picture) this.Picture picture this.Position position this.MayDraw true public virtual void Draw(SpriteBatch spriteBatch) if (MayDraw true) spriteBatch.Draw(Picture, Position, Color.White) Does the flicker problem occur because of the large image sizes? Could I do this with a shader instead? My background code works on with a graphic card with 60 FPS, but on a onboard graphic card with 30 FPS. I have 4 background layers, each layer has 4 pictures, in total about 15pictures are drawen with widths of 1920. |
12 | Increasing resolution of a texture? I'm doing some experiments on my own to improve my general skills with HLSL and so forth. In other words, I'm not doing any serious game development, but only looking to expand my knowledge within the field. I'm trying to figure out how I can increase the resolution of a texture, and multiply it X amount of times. Consider the following low resolution picture A typical scenario for me would be to scale up this picture 3 times in the shader without interpolation, and draw the new result I've been experimenting with a shader that transfers the small picture on to a texture as a variable on the shader. I got that far. Now I just need it to take that texture using tex2D or something else, and scale it up. How would I do that? |
12 | Pixel Collision Detecting corners How would I go about detecting the corners of a texture when I use pixel collision detection? I read about corner collision with rectangles, but I am unsure how to adapt it to my situation. Right now my map is tile based and I do rectangular collision until the player is intersecting with a blocked tile, then I switch to pixel collision. The effect I would like to achieve is when the player hits the corner of an object to push him around the side so he doesn't just hit the edge and stop. Any ideas? |
12 | Optimizing my 3D XNA game I've come to a point where optimizing my game is very much needed.My update() routine takes 0 2ms. My draw() routine takes about 100ms when drawing 3.5M triangles (Not the amount I really have to draw, but it's easier to debug.) I've noticed that reducing draw calls is more effective than reducing triangles per draw call (and keeping the amount of draw calls the same), and would primarily like to know how to do that. I've tried creating an array, adding items to that array every frame until it has about 65535 primitives in it (the maximum xna allows per draw call) and only drawing it then, but resizing the array is a terribly slow thing to do (drawing only 250k triangles takes about 500ms) So long story short In XNA, how do I properly optimize the drawing methods that use DrawUserIndexedPrimitives? Or primarily, how do I properly reduce draw calls? |
12 | How do I configure the clipping region when drawing with XNA's SpriteBatch? I have a SpriteBatch that is set to draw to a RenderTarget2D that is 500 pixels larger in both height and width. Whenever I draw to a point outside of the physical screen dimensions, it will not draw the object. I am performing some 3D transforms on the texture so I need the areas outside the screen to be drawn. I have tried setting culling to None and this had no effect. |
12 | Triangle accuracy picking for animated models in XNA I can do picking with triangle accuracy for non animated models, but I also have animated models in my game. How do I do picking on animated models? I use code based on this project for animation. My first idea for doing it is Calculate ray For each model If model bounding sphere collides with ray For each meshPart Make animation transformation Calculate transformed triangles in meshPart Test collisions of ray with resulting triangles Have you ever considered how to make something like this? |
12 | Help to understand directions of sprites in XNA If I want to move a sprite to the right and upwards in a 45 degree angle I use Vector2 direction new Vector2(1, 1) And if the sprite should move straight to right Vector2 direction new Vector2(1,0) But how would I do if I want another directions, lets say somewhere between this values? I have tested with some other values, but then the sprite either moves to fast and or in another direction than I expected!? I suspect it's about normalize!? Another thing I have problem with to understand. I'm doing a simple asteroids game as a task in a class in C and XNA. When the asteroids hit the window borders, I want them to bounce back in a random direction, but I can't do this before I understand how directions and Vector2 works. Help is preciated! Thanks! |
12 | C XNA Make rendered screen a texture2d I am working on a cool little city generator which makes cities in the isometric perspective. However, a problem arose where if the grid size was over a certain limit it would have awful lag. I found the main problem to be in the draw method. So I took the precautionary step of rendering only items that were onscreen. This fixed the lag but, not by much. The idea I have is to render the frame once and take a snapshot. Then, display that as a texture2d on screen. This way I don't have to render 1,000,000 objects every frame since they don't change anyways. TL DR I want to Take a snapshot of an already rendered frame Turn it into a Texture2D Render that to the screen instead of all the objects. Any help appreciated. |
12 | 2D Magnet like repelling behavior If somebody wanted to develop a system between two intersecting rectangles so that the rectangles would, in a gradual process, push eachother away from one another until no longer intersecting, with the repelling force being stronger depending upon how deep the intersection is... what would the math look like? |
12 | How to create biomes I am creating an 2D XNA Tile Based Platformer. I have a tile engine and a world terrain generator. However, I am trying to create biomes or areas, For example, Desert in one part of the world, ocean on the ends, City in the middle, forests scattered around etc. I can easily make it generate them, but My problem is defining the actual areas to be generated in. |
12 | Why does XNA create two GraphicsDeviceManager services? While working with XNA today, I looked at the debugger information for Game.Services to retrieve the GraphicsDeviceManager so that a component could utilize it. Instead, I found two different objects IGraphicsDeviceManager, GraphicsDeviceManager KeyValuePair lt Type, object gt IGraphicsDeviceService, GraphicsDeviceManager KeyValuePair lt Type, object gt Or rather, what I assume to be one instance of an object, but indexed according to two different interfaces. Why? (For context, I'm trying to understand all the different Graphics Device classes so I can make a ScreenComponent that moves it cleanly away from the main Game object.) |
12 | Why is XmlSerializer adding junk to the end of my file? I'm making a game and I am serializing the save game data. The data is simply a few lists of bools, ints and floats. But about 50 of the time I get an error when the data tries to save or load that says "There is an error in XML document." The error is always located at the end of the file, even after it has changed size or I have added other variables. It appears that very last part of the XML data is getting copied twice. The last line of the XML should read lt LevelStats gt But when an error occurs it often reads lt LevelStats gt gt Or lt LevelStats gt tats gt Or some other small part of the last line duplicated. Here is the class I am serializing using System using System.Collections.Generic using System.Linq using System.Text using System.Xml.Serialization using Microsoft.Xna.Framework.Storage using System.IO namespace Jetpack.Classes Serializable public struct LevelStats Player Bests public List lt float? gt fTimeList public List lt int? gt iScoreList public List lt int? gt iFuelList Time public List lt bool gt bBronzeTimeList public List lt bool gt bSilverTimeList public List lt bool gt bGoldTimeList Score public List lt bool gt bBronzeScoreList public List lt bool gt bSilverScoreList public List lt bool gt bGoldScoreList Fuel public List lt bool gt bBronzeFuelList public List lt bool gt bSilverFuelList public List lt bool gt bGoldFuelList Level Complete public List lt bool gt bIsLevelComplete And here are my methods for saving the loading the data region Save amp Load Level Stats public static void SaveLevelStats(LevelStats levelStats, string filename) Get the path of the save game string fullpath System.IO.Path.Combine(Directory.GetCurrentDirectory(), filename) Open the file, creating it if necessary FileStream stream File.Open(fullpath, FileMode.OpenOrCreate) try Convert the object to XML data and put it in the stream XmlSerializer serializer new XmlSerializer(typeof(LevelStats)) serializer.Serialize(stream, levelStats) finally Close the file stream.Close() public static LevelStats LoadLevelStats(string filename) LevelStats levelStats Get the path of the save game string fullpath System.IO.Path.Combine((Directory.GetCurrentDirectory()), filename) Open the file FileStream stream File.Open(fullpath, FileMode.OpenOrCreate, FileAccess.Read) try Read the data from the file XmlSerializer serializer new XmlSerializer(typeof(LevelStats)) levelStats (LevelStats)serializer.Deserialize(stream) finally Close the file stream.Close() return (levelStats) endregion Why am I getting the error above? |
12 | Vector3 vs. Vector2 performance, usage? I'm currently playing around with XNA, and creating a simple 2D platformer. I was thinking of adding multiple layers to make it a little bit of challenge. In stead of having a Vector2 for my positions, I now use a Vector3, solely to use it's Z as layer depth. However, since you can't use operators between Vector2 and Vector3 for some unknown reason 1 , I ended up changing all other Vector2s in my game, such as acceleration, speed and offset, so I can do things like position offset without errors. I also changed my rotation variable from float to Vector3, and I use the Z value to rotate my textures. I'm planning to use the X and Y to scale flip my textures, so you get the Super Paper Mario effect. However, after changing all these Vector2s in Vector3s, I felt a little bad about it. How does this effect the performance of games? I know I shouldn't have to worry about performance in my little platformer game, but I'm just curious about it. Is there any notable performance between Vector2s and Vector3s, for example when adding or multiplying them, or when calling Normalize, Transform, or Distance? 1 Just a side question, why are there no operators for calculations between Vector3 and Vector2? |
12 | XNA seams between 3d primitives in tiled terrain Every time I draw two primitives side by side, in this case two quads, I always get this seam like tearing effect right along the sides of them. I'd like to think there is just an easy fix, but the only way I can think of would be reworking my indices, which I think would compromise my ability to draw textures. If anyone reading this can think of any fix, that would be great. Thanks in advance. |
12 | Dealing with 2D pixel shaders and SpriteBatches in XNA 4.0 component object game engine? I've got a bit of experience with shaders in general, having implemented a couple, very simple, 3D fragment and vertex shaders in OpenGL WebGL in the past. Currently, I'm working on a 2D game engine in XNA 4.0 and I'm struggling with the process of integrating per object and full scene shaders in my current architecture. I'm using a component entity design, wherein my "Entities" are merely collections of components that are acted upon by discreet system managers (SpatialProvider, SceneProvider, etc). In the context of this question, my draw call looks something like this SceneProvider Draw(GameTime) calls... ComponentManager Draw(GameTime, SpriteBatch) which calls (on each drawable component) DrawnComponent Draw(GameTime, SpriteBatch) The SpriteBatch is set up, with the default SpriteBatch shader, in the SceneProvider class just before it tells the ComponentManager to start rendering the scene. From my understanding, if a component needs to use a special shader to draw itself, it must do the following when it's Draw(GameTime, SpriteBatch) method is invoked public void Draw(GameTime gameTime, SpriteBatch spriteBatch) spriteBatch.End() spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, EffectShader, ViewMatrix) Draw things here that are shaded by the "EffectShader." spriteBatch.End() spriteBatch.Begin( same settings that were set by SceneProvider to ensure the rest of the scene is rendered normally ) My question is, having been told that numerous calls to SpriteBatch.Begin() and SpriteBatch.End() within a single frame is terrible for performance and creates a number of special cases for my drawing logic, is there a better way to do this? Is there a way to instruct the currently running SpriteBatch to simply change the Effect shader it is using for this particular draw call and then switch it back before the function ends? |
12 | What is the best way to implement dialogs in an xna game? I want to implement some startup dialogs, for selecting game parameters, etc. The obvious (and I suppose naive) choice is to just use windows forms (I'm not really planning on porting this game to anything other than windows). But implementing this seems to be a real pain, i.e. can't use ShowDialog, and if I use Show() I have the question of how to return the result to the main loop. I was wondering if there's an established way to implement dialogs (radio buttons, combo boxes, text boxes, etc) in XNA (maybe some libraries) or is it just a case of reinventing the wheel each time? Just looking for some general advice on this issue before I spend too much time thrashing around trying different things. |
12 | How can I deal with actor translations and other "noise" in third party motion capture data? I'm working on a game, and I've run into a problem with motion capture data. My team is using 3DS Max 2011 and trying to put free motion capture files on our models. The problem we're having is it has become extremely hard to find motion capture data that stays in place. We've found some great motion captures of things like walking and jumping but the actors themselves move within the data, so when we attach these animations to our models and bring them into XNA, the models walk forward even when they should technically be standing still (and then there's also the problem of them resetting at the end of the animation). How can we clean up, at runtime or asset processing time, the animation in these motion capture files? |
12 | Algorithm to find all tiles within a given radius on staggered isometric map Given staggered isometric map and a start tile what would be the best way to get all surrounding tiles within given radius(middle to middle)? I can get all neighbours of a given tile and distance between each of them without any problems but I'm not sure what path to take after that. This feature will be used quite often (along with A ) so I'd like to avoid unecessary calculations. If it makes any difference I'm using XNA and each tile is 64x32 pixels. |
12 | How would I handle input with a Game Component? I am currently having problems from finding my way into the component oriented XNA design. I read an overview over the general design pattern and googled a lot of XNA examples. However, they seem to be right on the opposite site. In the general design pattern, an object (my current player) is passed to InputComponent update(Player). This means the class will know what to do and how this will affect the game (e.g. move person vs. scroll text in a menu). Yet, in XNA GameComponent update(GameTime) is called automatically without a reference to the current player. The only XNA examples I found built some sort of higher level Keyboard engine into the game component like this class InputComponent GameComponent public void keyReleased(Keys) public void keyPressed(Keys) public bool keyDown(Keys) public void override update(GameTime gameTime) compare previous state with current state and determine if released, pressed, down or nothing Some others went a bit further making it possible to use a Service Locator by a design like this interface IInputComponent public void downwardsMovement(Keys) public void upwardsMovement(Keys) public bool pausedGame(Keys) determine which keys pressed and what that means can be done for different inputs in different implementations public void override update(GameTime) Yet, then I am wondering if it is possible to design an input class to resolve all possible situations. Like in a menu a mouse click can mean "click that button", but in game play it can mean "shoot that weapon". So if I am using such a modular design with game components for input, how much logic is to be put into the InputComponent KeyboardComponent GamepadComponent and where is the rest handled? What I had in mind, when I heard about Game Components and Service Locator in XNA was something like this use Game Components to run the InputHandler automatically in the loop use Service Locator to be able to switch input at runtime (i.e. let player choose if he wants to use a gamepad or a keyboard or which shall be player 1 and which player 2). However, now I cannot see how this can be done. First code example does not seem flexible enough, as on a game pad you could require some combination of buttons for something that is possible on keyboard with only one button or with the mouse) The second code example seems really hard to implement, because the InputComponent has to know in which context we are currently. Moreover, you could imagine your application to be multi layered and let the key stroke go through all layers to the bottom layer which requires a different behaviour than the InputComponent would have guessed from the top layer. The general design pattern with passing the Player to update() does not have a representation in XNA and I also cannot see how and where to decide which class should be passed to update(). At most time of course the player, but sometimes there could be menu items you have to or can click I see that the question in general is already dealt with here, but probably from a more elobate point of view. At least, I am not smart enough in game development to understand it. I am searching for a rather code based example directly for XNA. And the answer there leaves (a noob like) me still alone in how the object that should receive the detected event is chosen. Like if I have a key up event, should it go to the text box or to the player? |
12 | How can I support more than one resolution language on WP7 8? I want that my Windows Phone game runs on the following three resolutions 480x800, 768x1280 and 720x1280. And maybe later on 1920x1080. But in the XAP file information, it's just written quot Resolution(s) WVGA quot . What can I support more resolutions than just WVGA? In addition, I want to support more than one language. At the moment, I can just choose English in the Dev Center menu, but I want to support French, Spanish and German too. How can I support French, Spanish and German? I don't know how to add these languages. I uploaded my XAP file in the Dev Center and it gives me the following informations Select a XAP above to view or edit its Store listing and other info. XAP version number 1.0.0.0 XAP details detected from file File name WindowsPhoneGame2.xap File size 167 KB Supported OS 7.1, 8.0 Resolution(s) WVGA Language(s) EnglishNorthAmerica Capabilities ID CAP NETWORKING XAP's Store listing info A XAP file can contain multiple languages. Select a language to add Store listing info specific for that language. English Description for the Store |
12 | Client and Server game update speed I am working on a simple two player networked asteroids game using XNA and the Lidgren networking library. For this set up I have a Lidgren server maintaining what I want to be the true state of the game, and the XNA game is the Lidgren client. The client sends key inputs to the server, and the server process the key inputs against game logic, sending back updates. (This seemed like a better idea then sending local positions to the server.) The client also processes the key inputs on its own, so as to not have any visible lag, and then interpolates between the local position and remote position. Based on what I have been reading this is the correct way to smooth out a networked game. The only thing I don t get is what value to use as the time deltas. Currently every message the server sends it also sends a delta time update with it, which is time between the last update. The client then saves this delta time to use for its local position updates, so they can be using roughly the same time deltas to calculate position updates. I know the XNA game update gets called 60 times a second, so I set my server to update the game state at the same speed. This will probably only work as long as the game is working on a fixed time step and will probably cause problems if I want to change that in the future. The server sends updates to clients on another thread, which runs at 10 updates per second to cut down on bandwidth. I do not see noticeable lag in movement and over time if no user input is received the local and remote positions converge on each other as they should. I am also not currently calculating for any latency as I am trying to go one step at a time. So my question is should the XNA client be using its current game time to update the local game state and not being using time deltas sent by the server? If I should be using the clients time delta between updates how do I keep it in line with how fast the server is updating its game state? |
12 | XNA 2D camera just part of screen Is it possible to use the 2D camera, but just for a part of the screen? Perhaps I want some info on the screen about score and other things, but I want that at a fixed place, just like when not using a 2D camera? |
12 | Detecting Hitbox Collisions (Rectangle) So I have some Hitboxes set up on 2 classes, HealthPickup and Player. public static Rectangle Hitbox public override void Initialize() Hitbox new Rectangle(Pos.X, Pos.Y, 32, 32) That's just general code, there are other things in the classes too. So what I want to know is why this doesn't work This is in the HealthPickup class' Update function. if (Hitbox.Intersects(Player.Hitbox)) Console.Beep() Doesn't work if I put it in the main update function either. Am I missing something? |
12 | Collisions and Lists I've run into an issue that breaks my collisions. Here's my method Gather Input Project Rectangle Check for intersection and ispassable Update The update method is built on object position seconds passed velocity speed. Input changes velocity and is normalized if 1. This method works well with just one object comparison, however I pass a list or a for loop to the collision detector and velocity gets changed back to a non zero when the list hits an object that passes the test and the object can pass through. Any solutions would be much appreciated. Side note is there a more proper way to simulate movement? |
12 | Trying to understand the XNA fixed time step game loop logic I came across the blog post Understanding GameTime, and after lots of reading on fixed time steps in game loops this is the approach I would like to take. In summary, this is the logic from the post Set the desired time spent in Update Draw as 1 60 of a second (fixed 60 fps). If time elapsed since last Update Draw is exactly 1 60 of a second Call Update Call Draw Tick (Game loops.) If time elapsed since last Update Draw takes less than 1 60 of a second Call Update Call Draw Look at the Clock (Time left over? Wait.) Tick (Game loops.) If time elapsed since last Update Draw takes more than 1 60 of a second? Call Update (Until we catch up.) Call Draw Tick (Game loops.) I guess the two parts I'm having trouble understanding is in 3, how would the waiting be accomplished since thread sleeps are often not accurate enough, and what does it mean in 4 to call update until we catch up? Catch up to what since the time elapsed is already greater than our target 60 fps? |
12 | XNA 3D AABB collision detection and response I've been fiddling around with 3D AABB collision in my voxel engine for the last couple of days, and every method I've come up with thus far has been almost correct, but each one never quite worked exactly the way I hoped it would. Currently what I do is get two bounding boxes for my entity, one modified by the X translation component and the other by the Z component, and check if each collides with any of the surrounding chunks (chunks have their own octrees that are populated only with blocks that support collision). If there is a collision, then I cast out rays into that chunk to get the shortest collision distance, and set the translation component to that distance if the component is greater than the distance. The problem is that sometimes collisions aren't even registered. Here's a video on YouTube that I created showing what I mean. I suspect the problem may be with the rays that I cast to get the collision distance not being where I think they are, but I'm not entirely sure what would be wrong with them if they are indeed the problem. Here is my code for collision detection and response in the X direction (the Z direction is basically the same) create the XZ offset vector Vector3 offsXZ new Vector3( ( translation.X gt 0.0f ) ? SizeX 2.0f ( translation.X lt 0.0f ) ? SizeX 2.0f 0.0f, 0.0f, ( translation.Z gt 0.0f ) ? SizeZ 2.0f ( translation.Z lt 0.0f ) ? SizeZ 2.0f 0.0f ) X physics BoundingBox boxx GetBounds( translation.X, 0.0f, 0.0f ) if ( translation.X gt 0.0f ) foreach ( Chunk chunk in surrounding ) if ( chunk.Collides( boxx ) ) float dist GetShortestCollisionDistance( chunk, Vector3.Right, offsXZ ) 0.0001f if ( dist lt translation.X ) translation.X dist else if ( translation.X lt 0.0f ) foreach ( Chunk chunk in surrounding ) if ( chunk.Collides( boxx ) ) float dist GetShortestCollisionDistance( chunk, Vector3.Left, offsXZ ) 0.0001f if ( dist lt translation.X ) translation.X dist And here is my implementation for GetShortestCollisionDistance private float GetShortestCollisionDistance( Chunk chunk, Vector3 rayDir, Vector3 offs ) int startY (int)( SizeY 2.0f ) int endY (int)( SizeY 2.0f ) int incY (int)Cube.Size float dist Chunk.Size for ( int y startY y lt endY y incY ) Position is the center of the entity's bounding box Ray ray new Ray( new Vector3( Position.X offs.X, Position.Y offs.Y y, Position.Z offs.Z ), rayDir ) Chunk.GetIntersections(Ray) returns Dictionary lt Block, float? gt foreach ( var pair in chunk.GetIntersections( ray ) ) if ( pair.Value.HasValue amp amp pair.Value.Value lt dist ) dist pair.Value.Value return dist I realize some of this code can be consolidated to help with speed, but my main concern right now is to get this bit of physics programming to actually work. |
12 | Custom effects on Model in XNA If I have a Model that is drawn with a different effect occasionally, what is the typical approach to this? Models have effects stored in each of their meshes, and you seem to be forced to use those. Typically this is done foreach (ModelMesh mesh in model.Meshes) foreach (Effect effect in mesh.Effects) effect.Parameters "World" .SetValue(world) Other stuff related to this specific effect is done here. mesh.Draw() I want to be able to do this foreach (ModelMesh mesh in model.Meshes) myEffect.CurrentTechnique.Passes 0 .Apply() mesh.Draw() Mesh will be drawn with "myEffect". What are our options? |
12 | Monogame XNA Multple 2D Cameras (Rectangle) on screen I recently started building a simple 2D roguelike game using Monogame 3.4. I was keen on building the game "engine" myself as I saw it as a fun learning curve. Monogame was pretty much the best option for me to get started as I'm a C dev by profession. After getting my sprite to run around on the screen, I figured I probably need a proper level to continue with the more interesting stuff. So I decided to build a level builder for the game. I've been struggling and digging around tutorials regarding building a 2D Camera. I used this camera tutorial and I preferred this specific implementation. My only problem is, currently, I have two Rectangles (Cameras) on my screen. The Rectangle on the left represents a scrollable panel with all the available sprites but is also a sort of overlay. Underneath it, the level "map" is drawn. My question is simply, how would I enable my level Rectangle to scroll past the overlay to view the left hand side of it, which is currently being obscured by the panel. Relevant code files are here I would appreciate all the help I can get. Thanks! |
12 | Making multiple VertexPositionColor variables in the same class? XNA I have studying XNA on my spare time for about a year now and I could use some professional help on this issue. Any time given to my problem is appreciated. I have two VertexPositionColor variables both of which are placed into two separate vertex buffers to draw up three triangles basicEffect new BasicEffect(GraphicsDevice) VertexPositionColor vertices new VertexPositionColor 6 vertices 0 new VertexPositionColor(new Vector3(0, 1, 0), Color.Red) vertices 1 new VertexPositionColor(new Vector3( 1, 1, 0), Color.Green) vertices 2 new VertexPositionColor(new Vector3(1, 1, 0), Color.Blue) vertices 3 new VertexPositionColor(new Vector3(0.05f, 1, 0), Color.Yellow) vertices 4 new VertexPositionColor(new Vector3( 1, 1, 0), Color.Blue) vertices 5 new VertexPositionColor(new Vector3( 1, 1, 0), Color.Pink) vertexBuffer new VertexBuffer(GraphicsDevice, typeof(VertexPositionColor), 6, BufferUsage.WriteOnly) vertexBuffer.SetData lt VertexPositionColor gt (vertices) VertexPositionColor vertices2 new VertexPositionColor 3 vertices2 0 new VertexPositionColor(new Vector3(0, 1, 0), Color.Blue) vertices2 1 new VertexPositionColor(new Vector3( 1, 1, 0), Color.Red) vertices2 2 new VertexPositionColor(new Vector3(0.9f, 0.9f, 0), Color.Orange) vertexBuffer2 new VertexBuffer(GraphicsDevice, typeof(VertexPositionColor), 6, BufferUsage.WriteOnly) vertexBuffer2.SetData lt VertexPositionColor gt (vertices2) I then use the draw function to draw all three triangles .. public override void Draw(GameTime gameTime) basicEffect.World world basicEffect.View view basicEffect.Projection projection basicEffect.VertexColorEnabled true GraphicsDevice.SetVertexBuffer(vertexBuffer) GraphicsDevice.SetVertexBuffer(vertexBuffer2) RasterizerState rasterizerState new RasterizerState() rasterizerState.CullMode CullMode.None GraphicsDevice.RasterizerState rasterizerState foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes) pass.Apply() GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, 3) base.Draw(gameTime) But it does not draw all three triangles. I have tried various variations and all that gets drawn is either the last vertex buffer or the first one. I know it would be more efficient to place them all in the same buffer or have them used with indices, but in the future I will run into issues where I am going to need more than one buffer to draw something and I want to be prepared. What is the problem here and how do I draw more than one vertex buffer at a time? |
12 | Abstracting entity caching in XNA I am in a situation where I am writing a framework in XNA and there will be quite a lot of static (ish) content which wont render that often. Now I am trying to take the same sort of approach I would use when doing non game development, where I don't even think about caching until I have finished my application and realise there is a performance problem and then implement a layer of caching over whatever needs it, but wrap it up so nothing is aware its happening. However in XNA the way we would usually cache would be drawing our objects to a texture and invalidating after a change occurs. So if you assume an interface like so public interface IGameComponent void Update(TimeSpan elapsedTime) void Render(GraphicsDevice graphicsDevice) public class ContainerComponent IGameComponent public IList lt IGameComponent gt ChildComponents get private set Assume constructor public void Update(TimeSpan elapsedTime) Update anything that needs it public void Render(GraphicsDevice graphicsDevice) foreach(var component in ChildComponents) draw every component Then I was under the assumption that we just draw everything directly to the screen, then when performance becomes an issue we just add a new implementation of the above like so public class CacheableContainerComponent IGameComponent private Texture2D cachedOutput private bool hasChanged public IList lt IGameComponent gt ChildComponents get private set Assume constructor public void Update(TimeSpan elapsedTime) Update anything that needs it set hasChanged to true if required public void Render(GraphicsDevice graphicsDevice) if(hasChanged) CacheComponents(graphicsDevice) Draw cached output private void CacheComponents(GraphicsDevice graphicsDevice) Clean up existing cache if needed var cachedOutput new RenderTarget2D(...) graphicsDevice.SetRenderTarget(renderTarget) foreach(var component in ChildComponents) draw every component graphicsDevice.SetRenderTarget(null) Now in this example you could inherit, but your Update may become a bit tricky then without changing your base class to alert you if you had changed, but it is up to each scenario to choose if its inheritance implementation or composition. Also the above implementation will re cache within the rendering cycle, which may cause performance stutters but its just an example of the scenario... Ignoring those facts as you can see that in this example you could use a cache able component or a non cache able one, the rest of the framework needs not know. The problem here is that if lets say this component is drawn mid way through the game rendering, other items will already be within the default drawing buffer, so me doing this would discard them, unless I set it to be persisted, which I hear is a big no no on the Xbox. So is there a way to have my cake and eat it here? One simple solution to this is make an ICacheable interface which exposes a cache method, but then to make any use of this interface you would need the rest of the framework to be cache aware, and check if it can cache, and to then do so. Which then means you are polluting and changing your main implementations to account for and deal with this cache... I am also employing Dependency Injection for alot of high level components so these new cache able objects would be spat out from that, meaning no where in the actual game would they know they are caching... if that makes sense. Just incase anyone asked how I expected to keep it cache aware when I would need to new up a cachable entity. |
12 | How can I get a list of sprites which are being drawn in the current viewport using XNA? Just starting out using XNA to draw 3D scenes and have a question about determining which objects are currently visible. If I load many thousands of sprites and shapes in a scene, then render the current view from a camera, is it possible to actually find (e.g. list to a text file) the IDs of those visible objects? I guess another way to ask this is to say how can I get a list of objects (e.g. sprites) which are being drawn in the current viewport? |
12 | Collisions and Lists I've run into an issue that breaks my collisions. Here's my method Gather Input Project Rectangle Check for intersection and ispassable Update The update method is built on object position seconds passed velocity speed. Input changes velocity and is normalized if 1. This method works well with just one object comparison, however I pass a list or a for loop to the collision detector and velocity gets changed back to a non zero when the list hits an object that passes the test and the object can pass through. Any solutions would be much appreciated. Side note is there a more proper way to simulate movement? |
12 | Implementing a wheeled character controller I'm trying to implement Boxycraft's character controller in XNA (with Farseer), as Bryan Dysmas did (minus the jumping part, yet). My current implementation seems to sometimes glitch in between two parallel planes, and fails to climb 45 degree slopes. (YouTube videos in links, plane glitch is subtle). How can I fix it? From the textual description, I seem to be doing it right. (Note my coordinates system is top for positive Y). Here is my implementation (it seems like a huge wall of text, but it's easy to read. I wish I could simplify and isolate the problem more, but I can't) public Body TorsoBody get private set public PolygonShape TorsoShape get private set public Body LegsBody get private set public Shape LegsShape get private set public RevoluteJoint Hips get private set public FixedAngleJoint FixedAngleJoint get private set public AngleJoint AngleJoint get private set ... this.TorsoBody BodyFactory.CreateRectangle(this.World, 1, 1.5f, 1) this.TorsoShape new PolygonShape(1) this.TorsoShape.SetAsBox(0.5f, 0.75f) this.TorsoBody.CreateFixture(this.TorsoShape) this.TorsoBody.IsStatic false this.LegsBody BodyFactory.CreateCircle(this.World, 0.5f, 1) this.LegsShape new CircleShape(0.5f, 1) this.LegsBody.CreateFixture(this.LegsShape) this.LegsBody.Position 0.75f Vector2.UnitY this.LegsBody.IsStatic false this.Hips JointFactory.CreateRevoluteJoint(this.TorsoBody, this.LegsBody, Vector2.Zero) this.Hips.MotorEnabled true this.AngleJoint new AngleJoint(this.TorsoBody, this.LegsBody) this.FixedAngleJoint new FixedAngleJoint(this.TorsoBody) this.Hips.MaxMotorTorque float.PositiveInfinity this.World.AddJoint(this.Hips) this.World.AddJoint(this.AngleJoint) this.World.AddJoint(this.FixedAngleJoint) ... public void Move(float m) 1, 0, 1 this.Hips.MotorSpeed 0.5f m |
12 | Cubic bezier for easing? I would like to find out what Y is if X is a certain number from a cubic bezier curve to make a custom easing function, like it's done on this site http cubic bezier.com Does anyone know a formula or a function to find Y if X is something of a cubic bezier? (Coding in C XNA) |
12 | Rotating sprite 180 deg I should say first, that I have the rotation down. Its just that I want my square to rotate exactly 180 degrees. Currently, it will rotate but it will rotate but by less each jump. So after several jumps it will be moving on one of its side. There's not much code to show but I'll show you how I'm rotating if (jumped) roation 0.1f playerVel.Y gravity I haven't initialized rotation to anything. I've also tried using some Math functions but I just get the same result. |
12 | Effects to make a speeding spaceship look faster I have a spaceship and I've created a "boost" functionality that speeds up my spaceship, what effects should I implement to create the impression of high speed? I was thinking of making everything except my spaceship blurry but I think there would be something missing. Any ideas? Btw. I am working in XNA C but if you aren't familiar to XNA describing some effects is still useful. The Game is 3d and i've attached some printscreens of the game This is in normal mode ( none boosted ) and here is the boosted mode ( the craft speeds up forward while the camera speeds in its normal speed , the non boosted speed ) |
12 | XNA game looks laggy below 100 fps? My xna game is running at about 70 90fps and it looks laggy at this fps. I'm using fraps to record the fps and I have a 120hz monitor, over 120hz looks fine but I can't understand why it feels like it's lagging so much at high fps . |
12 | Is 2 lines of push pop code for each pre draw state too many? I'm trying to simplify vector graphics management in XNA currently by incorporating state preservation. 2X lines of push pop code for X states feels like too many, and it just feels wrong to have 2 lines of code that look identical except for one being push() and the other being pop(). The goal is to eradicate this repetitiveness,and I hoped to do so by creating an interface in which a client can give class struct refs in which he wants restored after the rendering calls. Also note that many beginner programmers will be using this, so forcing lambda expressions or other advanced C features to be used in client code is not a good idea. I attempted to accomplish my goal by using Daniel Earwicker's Ptr class public class Ptr lt T gt Func lt T gt getter Action lt T gt setter public Ptr(Func lt T gt g, Action lt T gt s) getter g setter s public T Deref get return getter() set setter(value) an extension method doesn't work for structs since this is just syntatic sugar public static Ptr lt T gt GetPtr lt T gt (this T obj) return new Ptr lt T gt ( () gt obj, v gt obj v ) and a Push Function returns a Pop Action for later calling public static Action Push lt T gt (ref T structure) where T struct T pushedValue structure copies the struct data Ptr lt T gt p structure.GetPtr() return new Action( () gt p.Deref pushedValue ) However this doesn't work as stated in the code. How might I accomplish my goal? Example of code to be refactored protected override void RenderLocally (GraphicsDevice device) if (!(bool)isCompiled) Compile() TODO make sure state settings don't implicitly delete any buffers resources RasterizerState oldRasterState device.RasterizerState DepthFormat oldFormat device.PresentationParameters.DepthStencilFormat DepthStencilState oldBufferState device.DepthStencilState Rendering code device.RasterizerState oldRasterState device.DepthStencilState oldBufferState device.PresentationParameters.DepthStencilFormat oldFormat |
12 | Can I load a SpriteFont without a content project? I'm developing a game in XNA, however, I do not want to use a content project. I'm loading all my textures through different means, and I'd also like to load my fonts without a content project. Is there any quick way to maybe include the SpriteFont in the main game project? |
12 | XNA game looks laggy below 100 fps? My xna game is running at about 70 90fps and it looks laggy at this fps. I'm using fraps to record the fps and I have a 120hz monitor, over 120hz looks fine but I can't understand why it feels like it's lagging so much at high fps . |
12 | Multi colored text and kerning Drawing multi colored text or highlighted text in XNA MonoGame is pretty annoying, and the standard way I've seen to do it is to just to make multiple SpriteBatch.DrawString calls, and place them using the x coordinates given by SpriteFont.MeasureString. This is fine if you're highlighting whole words or blocks of text, but if you only want to highlight select letters inside of a word, you get a kerning nightmare Sometimes this looks alright, but not consistently and I can't think or find a good way to space out the letters properly. Therefore, I would like to know if there's either a better way to draw highlighted text like this in XNA MonoGame, or a way to pull kerning data out of a font so I can space the letters properly or some other fancy way to do it using masks or whatnot. Thanks in advance! |
12 | Why is my cursor not working if I add a scaling matrix? After moving the camera to any direction, my cursor isn't getting drawn on the correct position. For example I move my camera to the right, after that I click on the screen, but the cursor isn't getting drawn on the place I clicked. It's drawn somewhere else on the screen. Why is the cursor not getting drawn on the place I clicked? I need to scale the screen because I want to support different resolutions in a MonoGame project(see my other question) How can I use a camera matrix with different resolutions? I scale like this UPDATE I added the code that I'm using to get the cursor position, and the code that I'm using to draw the cursor. In addition, I use now Matrix.Invert(scaleMatrix camera.GetMatrix())), but it doesn't work. The cursor is still drawn on the wrong position. In my Player class, I get the position of the click(Tap) The Playerposition is the center of the camera public void Update(GameTime gameTime) while (TouchPanel.IsGestureAvailable) GestureSample gs TouchPanel.ReadGesture() switch (gs.GestureType) case GestureType.HorizontalDrag Playerposition new Vector2(gs.Delta.X game1.scaleX, gs.Delta.Y game1.scaleY) break case GestureType.VerticalDrag Playerposition new Vector2(gs.Delta.X game1.scaleX, gs.Delta.Y game1.scaleY) break case GestureType.Tap game1.CursorPosition new Rectangle((int)(gs.Position.X game1.scaleX), (int)(gs.Position.Y game1.scaleY), 10, 10) game1.Clicked true break In Game1 public const int VirtualScreenWidth 800 public const int VirtualScreenHeight 480 public float scaleX, scaleY private Vector3 screenScale protected override void LoadContent() scaleX (float)GraphicsDevice.Viewport.Width (float)VirtualScreenWidth scaleY (float)GraphicsDevice.Viewport.Height (float)VirtualScreenHeight screenScale new Vector3(scaleX, scaleY, 1.0f) protected override void Update(GameTime gameTime) player.Update(gameTime) Updating the camera position Newcameraposition new Vector2(player.Playerposition.X (float)VirtualScreenWidth 2, player.Playerposition.Y (float)VirtualScreenHeight 2) camera.Update(gameTime, Newcameraposition) InvertCursorPos Vector2.Transform(new Vector2(CursorPosition.X, CursorPosition.Y), Matrix.Invert(scaleMatrix camera.GetMatrix())) Calculate the cursor position if (Clicked true) CursorPosition new Rectangle((int)(InvertCursorPos.X Newcameraposition.X), (int)(InvertCursorPos.Y Newcameraposition.Y), 10, 10) Clicked false base.Update(gameTime) Drawing protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.CornflowerBlue) var scaleMatrix Matrix.CreateScale( screenScale) spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.AnisotropicClamp, DepthStencilState.None, RasterizerState.CullNone, null, scaleMatrix camera.GetMatrix()) Drawing the cursor spriteBatch.Draw(CursorSprite, CursorPosition, null, Color.White, 0, Vector2.Zero, SpriteEffects.None, 1) spriteBatch.End() |
12 | Determining my playable area field of view Contrary to what I found searching for the answer, I'm not trying to see whether a character is in view of another character. What I need to find out is the size of the field of view. This is because I'm using Mercury Particle Engine in a 3D space, and while MPE emitters take parameters ranging from (0,0) being the upper left corner of the screen to (graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight) being the lower right corner of the screen, the positioning of enemy ships use Vector3 values, where (0,0,0) would be the exact center of the screen. Since my ships don't move along the Z axis, this isn't a problem. What is a problem, however, is translating their coordinates in 3D space to the correct particle emitter positions when I need to show them exploding. This is what I'm currently using to create the perspective field of view projectionMatrix Matrix.CreatePerspectiveFieldOfView( MathHelper.ToRadians(45.0f), GraphicsDevice.DisplayMode.AspectRatio, 1250.0f, 1450.0f) And this is how I'm attempting to obtain the X and Y values for the particle emitter from the enemy ship position (however, the positions are not quite right with my math because I have the wrong constants) x ((float)graphics.PreferredBackBufferWidth 2) (((float)graphics.PreferredBackBufferWidth 1700) enemy i .position.X) y ((float)graphics.PreferredBackBufferHeight 2) (((float)graphics.PreferredBackBufferHeight 1100) enemy i .position.Y) That being said, how do I calculate the proper constants from the information on hand? |
12 | Need the co ordinates of innerPolygon Let say I have this diagram, Given that i have all the co ordinates of outer polygon and the distance between inner and outer polygon is d is also given. How to calculate the inner polygon co ordinates? Edit I was able to solved the issue by getting the mid points of all lines. From these mid points I can move d distance, So I can get three points. No I have 3 points and 3 slopes. From this, I can get three new equations. Simultaneously, solving the equation get the 3 points. |
12 | How to load textures at other times than startup in XNA using vb.net? I've encountered a problem with my game project lately. When I load more than a certain number of textures (around 1000) at startup I recieve an error regarding memory, because I have to use 32 bit in XNA. I am self taught and so have only basic knowledge of the "correct" ways to program a game. The project itself is getting very big and although I try to compress images together etc, I will have to use more than 1000 textures throughout the project. My question is this How can I load textures at other points of time than at startup in XNA, using vb.net? (I'm not using classes at all that I'm aware of, so I hope to stay away from that if possible) |
12 | How can I support different resolutions with Monogame? I want to support the following 4 resolutions in my Windows Phone 8 game 480 800, 768 1280, 720 1280, 1080 x 1920. How can I do that with Monogame? If I draw a sprite with Monogame, the sprite is not drawn on the right place in every resolution. For example, with a resolution of 768 1280, the sprite is drawn in the center of the screen, but if I use another resolution, the sprite is no more drawn in the center of the screen. What should I do so that the sprite is in every resolution on the same place? |
12 | XNA advanced rotation 3D I'm able to rotate any model with any angle I want, where I can not rotate my model around a given point. e.g My model rotates from the origin assigned in its .fpx file. I want it to rotate related to a point of its bottom plane, so that it is animated as falling |
12 | Eliminate delay between looping XNA songs? I'm making a game with XNA and trying to get some background music to loop correctly. Because the file is an MP3 of about 30 seconds in length, I instantiated it as a Song. I want it to loop perfectly, but even when I set the MediaPlayer.IsRepeating property to true, there is always a delay of about one second before the song starts up again. Is there any way to eliminate this delay such that the song loops instantly, so it can play more fluently? |
12 | How to I coordinate a camera with the eyes of a model? I am currently working on an FPS in XNA and I wanted to know how I would position the camera at the eyes of the model and whenever the model rotated or moved it's head (where the eyes are), the camera would move along with it. Also, whenever the player moves the camera (with their mouse) the model would turn it's head and eventually it's body. I believe this would reduce the need for constant transformations and the planning of cutscenes by having an animation play and the camera follow that animation. It would also cut the need for transforming the model constantly when I add a future multiplayer. I'm also open to any other ideas, so please, leave a comment letting me know what you think would be good and efficient. |
12 | Storing large array of tiles, but allowing easy access to data I've been thinking about this for a while. I have a 2D tile bases platformer in XNA with a large array of tile data, I've been running into memory problems with large maps. (I will add chunks soon!) Currently, Each tile contains an Item along with other properties like how its rotated, if it has forground background, etc. An Item is static and has properties like the name, tooltip, type of item, how much light it emits, the collision it does to player, etc. Examples public class Item public static List lt Item gt Items public Collision blockCollisionType public string nameOfItem public bool someOtherVariable,etc,etc public static Item Air public static Item Stone public static Item Dirt static Item() Items new List lt Item gt () (Stone new Item() nameOfItem "Stone", blockCollisionType Collision.Solid, ), (Air new Item() nameOfItem "Air", blockCollisionType Collision.Passable, ), Would be an Item, The array of Tiles would contain a Tile for each point, public class Tile public Item item What type it is public bool onBackground public int someOtherVariables,etc,etc Now, Most would probably use an enum, or a form of ID to identify blocks. Well my system is really nice just to find out about an item. I can simply do tiles x,y .item.Name To get the name for example. I realized my Item property of the tile is over 1000 Bytes! Wow! What I'm looking for is a way to use an ID (Int or byte depending on how many items) instead of an Item but still have a method for retreiving data about the type of item a tile contains. |
12 | Where do I place XNA content pipeline references? I am relatively new to XNA, and have started to delve into the use of the content pipeline. I have already figured out that tricky issue of adding a game library containing classes for any type of .xml file I want to read. Here's the issue. I am trying to handle the reading of all XML content through use of an XMLHandler object that uses the intermediate deserializer. Any time reading of such data is required, the appropriate method within this object would be called. So, as a simple example, something like this would occur when a character levels public Spell LevelUp(int levelAchived) XMLHandler.FindSkillsForLevel(levelAchived) This method would then read the proper .xml file, sending back the spell for the character to learn. However, the XMLHandler is having issues even being created. I cannot get it to use the using namespace of Microsoft.Xna.Framework.Content.Pipeline. I get an error on my using statement in the XMLHandler class using Microsoft.Xna.Framework.Content.Pipeline.Serialization.Intermediate The error is a typical reference error Type or namespace name "'Pipeline' does not exist in the namespace 'Microsoft.Xna.Framework.Content' (are you missing an assembly reference?)" I THINK this is because this namespace is already referenced in my game's content. I would really have no issue placing this object within my game's content (since that is ALL it deals with anyways), but the Content project does not seem capable of holding anything but content files. In summary, I need to use the Intermediate Deserializer in my main project's logic, but, as far as I can make out, I can't safely reference the associated namespace for it outside of the game's content. I'm not a terribly well versed programmer, so I may be just missing some big detail I've never learned here. How can I make this object accessible for all projects within the solution? I will gladly post more information if needed! |
12 | Non GPU Noise for 2D side view terrain generation? I really couldn't find a correct answer while scowering all the forums for Noise Generation. My goal is simple, I really want to have two distinct layers for my terrain, a white layer representing air, and a black layer representing earth. An algorithm will pick up from there. Most noise I found generated "Cloudy" textures, where I am looking for something along the lines of So far I have worked with Perlin Noise but adjusting my values yields no useful results. Does anyone have any ideas? |
12 | No output to screen using Multiple Render Targets and multisampling I'm having a little trouble with XNA, but I doubt it's specific to the framework. I draw a few 3d models to 1 rendertarget with multisampling turned on, and it works fine. If I draw the same scene to 2 rendertargets (of course the second one gets a different output (configured this in HLSL shaders)) with multisampling turned on, I get absolutely no output. Nothing. Blank. Also, when I render to both outputs but turn off multisampling, it works perfectly (but looks hideous due to a lack of antialiasing). The strange thing is This happens on my desktop (Nvidia GTX 560 Ti), but not on my laptop (Intel HD Graphics 4000, which sits on the CPU). On my laptop, it outputs just fine to both rendertargets and multisampling turned on. Can anybody explain what could be wrong? I won't copy all my code here but just to clarify graphics.PreferMultiSampling True RT Light New RenderTarget2D(device, ClientWidth, ClientHeight, False, SurfaceFormat.Color, DepthFormat.Depth24, 0, RenderTargetUsage.PreserveContents) RT Scene New RenderTarget2D(device, ClientWidth, ClientHeight, False, SurfaceFormat.Color, DepthFormat.Depth24, 0, RenderTargetUsage.PreserveContents) device.SetRenderTargets(RT Scene,RT Light) 'Draw Works but looks hideous graphics.PreferMultiSampling True RT Light New RenderTarget2D(device, ClientWidth, ClientHeight, False, SurfaceFormat.Color, DepthFormat.Depth24, 4, RenderTargetUsage.PreserveContents) RT Scene New RenderTarget2D(device, ClientWidth, ClientHeight, False, SurfaceFormat.Color, DepthFormat.Depth24, 4, RenderTargetUsage.PreserveContents) device.SetRenderTarget(RT Scene) 'Draw Works but obviously only draws to one rendertarget graphics.PreferMultiSampling True RT Light New RenderTarget2D(device, ClientWidth, ClientHeight, False, SurfaceFormat.Color, DepthFormat.Depth24, 4, RenderTargetUsage.PreserveContents) RT Scene New RenderTarget2D(device, ClientWidth, ClientHeight, False, SurfaceFormat.Color, DepthFormat.Depth24, 4, RenderTargetUsage.PreserveContents) device.SetRenderTargets(RT Scene,RT Light) 'Draw Works on my laptop, but not on my desktop. Again, to clarify The top picture is what my laptop shows (with multisampling and multiple render targets), and the bottom picture is what my desktop shows with the same settings |
12 | XNA MonoGame RenderTargets not working I'm having a problem with drawing 2 RenderTargets to the screen. using System using System.Collections.Generic using System.Linq using System.Text using Microsoft.Xna.Framework using Microsoft.Xna.Framework.Graphics using Microsoft.Xna.Framework.Input using Microsoft.Xna.Framework.Content namespace Please class Class1 RenderTarget2D rt Texture2D temp Vector2 v public Class1(Vector2 v,GraphicsDevice g) this.v v rt new RenderTarget2D(g,800,600) public void Draw(SpriteBatch sb,GraphicsDevice gd,ContentManager cm) gd.SetRenderTarget(rt) sb.Begin() sb.Draw(cm.Load lt Texture2D gt ("Untitled.png"),v,Color.White) sb.End() gd.SetRenderTarget(null) temp (Texture2D)rt sb.Begin() sb.Draw(temp, Vector2.Zero, Color.White) sb.End() Here's my draw function in the actual "game" protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.CornflowerBlue) base.Draw(gameTime) one.Draw(spriteBatch, graphics.GraphicsDevice, Content) two.Draw(spriteBatch, graphics.GraphicsDevice, Content) one and two have positions (100,200) and (300,200) respectively, so, they should be drawn 100 pixels apart, however, only two is being drawn with the rest of the screen black |
12 | How to finish a sprite animation before going back to default animation? I want to run a animation until it has gone through all the frames, even when the activation key is no longer held. After the animation is completely finished, it goes back to walking state. I also want to force the animation to finish first before the player can trigger the new animation. if (mCurrentState State.Walking) action "stand" Update Stand(gameTime) if (aCurrentKeyboardState.IsKeyDown(Keys.Left) true) action "run" feetPosition.X MOVE LEFT effect SpriteEffects.None Update Run(gameTime) else if (aCurrentKeyboardState.IsKeyDown(Keys.Right) true) action "run" feetPosition.X MOVE RIGHT effect SpriteEffects.FlipHorizontally Update Run(gameTime) if (aCurrentKeyboardState.IsKeyDown(Keys.Z) true) mCurrentState State.Hitting if (mCurrentState State.Hitting) action "hit" Update Hit(gameTime) mCurrentState State.Walking My Update Hit(GameTime gameTime) method is something like that. Amount of time between frames TimeSpan frameInterval Hit Time passed since last frame TimeSpan nextFrame Hit public void Update Hit(GameTime gameTime) Check if it is a time to progress to the next frame if (nextFrame Hit gt frameInterval Hit) Progress to the next frame in the row currentFrame Hit.X If reached end of the row advance to the next row, reset to the first frame if (currentFrame Hit.X gt sheetSize Hit.X) currentFrame Hit.X 0 currentFrame Hit.Y If reached last row in the frame sheet, jump to the first row again if (currentFrame Hit.Y gt sheetSize Hit.Y) currentFrame Hit.Y 0 Reset time interval for next frame nextFrame Hit TimeSpan.Zero else Wait for the next frame nextFrame Hit gameTime.ElapsedGameTime |
12 | Random enemy placement on a 2d grid I want to place my items and enemies randomly (or as randomly as possible). At the moment I use XNA's Random class to generate a number between 800 for X and 600 for Y. It feels like enemies spawn more towards the top of the map than in the middle or bottom. I do not seed the generator, maybe that is something to consider. Are there other techniques described that can improve random enemy placement on a 2d grid? |
12 | Ambient occlusion of cubes, a specific case After much fiddling around and thinking I've got my AO working on my game engine as intended except one specific case. When a block is nestled between others on two sides, but the corner block is missing, that corner doesn't get occluded. This isn't too shocking, because there's no logic to do otherwise. However, I can't think of a way to neatly solve that case. If I make it detect a block on each pair of sides, then check for the corner piece, we will end up with lots of broken AO in various scenarios, and that will be a lot of checks to boot. Here's the table I came up with today which finally solved the missing bits of my AO algorithms Click for larger view The logic in my code (C MonoGame) essentially enforces this table. If nobody comes up with anything better, I'll put a series of booleans in the checks for each side, then run through each combination and adjust as though a pair of side block were the corresponding corner block. |
12 | XNA Library DrawPrimitives throwing primitiveCount error I downloaded the project from here http silverlight.bayprince.com tutorials.php?tutorial 13 and tried adding a new OBJ file with a few thousand vertices listed. The classic teapot works but when I tried loading a different model with alot more vertices included, it suddenly throws this primitiveCount error when the DrawPrimitives gets called. EDIT The code includes a class that would read the data from the OBJ file. This will then return a VertexBuffer object back to the main program. The drawing starts when the Draw event is called. There are 417936 vertices created from the OBJ file and since I'm using a trianglelist, I divided the vertices by 3 to get the total primitives count. here's the code for the draw event private void DrawingSurface Draw(object sender, DrawEventArgs e) GraphicsDevice device GraphicsDeviceManager.Current.GraphicsDevice device.Clear(ClearOptions.Target ClearOptions.DepthBuffer, new Microsoft.Xna.Framework.Color(0, 0, 0, 0), 10.0f, 0) device.RasterizerState new RasterizerState() CullMode CullMode.None device.SetVertexBuffer( vertexBuffer) foreach (EffectPass pass in effect.CurrentTechnique.Passes) pass.Apply() device.SamplerStates 0 SamplerState.LinearClamp device.DrawPrimitives(PrimitiveType.TriangleList, 0, vertexBuffer.VertexCount 3) set camera effect.World Matrix.Identity effect.View Matrix.CreateLookAt(new Vector3( x, y, z), Vector3.Zero, Vector3.Up) effect.Projection Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, 2.0f, 1.0f, 100.0f) move camera along a circumference x (float)( radius Math.Sin( hAngle (Math.PI 180))) z (float)( radius Math.Cos( hAngle (Math.PI 180))) move camera along a circumference y (float)( radius Math.Cos( hAngle (Math.PI 180))) e.InvalidateSurface() then the error occurs on the DrawPrimitives. Any clues about this? |
12 | What is the best way to draw a big 3D model I am currently using ModelMesh.Draw() to draw the each mesh of the model and thus the whole model. Note that my models are very heavy around 30MB of data, I think if there is any other way to draw the models which is more efficient then performance of my application will better. |
12 | up vector for quaternion First, I know there's a question exactly like mine, and some ohter really close, but my implementation of the solutions didn't work at all. Ok, now to the question. I created some forms of camera based on quaternions, however, for my orbit chase camera every quaternion I create will roll the camera in an uncontrollable manner. What I want is a function like Unity's Quaternion.LookRotation where you can pass an up vector. This is a simplification current attempt of implementation Vector3 target Position Because we're looking at the origin target.Normalize() float cosine Vector3.Dot(Vector3.Forward, target) Vector3 axis Vector3.Cross(Vector3.Forward, target) Rotation Quaternion.CreateFromAxisAngle(axis, (float)Math.Acos(cosine)) Trying to unroll up vector to Vector3.Up based on the other answer but results were unchanged Vector3 rolledUp Vector3.Transform(Vector3.Up, Rotation) Vector3 right Vector3.Cross(target, Vector3.Up) Vector3 newUp Vector3.Cross(right, target) Vector3 axis2 Vector3.Cross(rolledUp, newUp) float angle2 (float) Math.Acos(Vector3.Dot(rolledUp,newUp)) Rotation Quaternion.CreateFromAxisAngle(axis2, angle2) Rotation return Matrix.CreateLookAt( cameraPosition Position, cameraTarget Vector3.Transform(Vector3.Forward, Rotation), cameraUpVector Vector3.Transform(Vector3.Up, Rotation)) If my sleepiness got in the way of my clarity, here's what I have and here's what I want |
12 | 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. |
12 | How to make HLSL effect just for lighting without texture mapping? I created an effect and just want to use lightning but in default effect that XNA create we should do texture mapping or the model appears 'RED', because of this lines of code in the effect file float4 PixelShaderFunction(VertexShaderOutput input) COLOR0 float4 output float4(1,0,0,1) return output If I want to see my model, I must do texture mapping by UV coordinates. But my model does not have UV coordinates assigned or its UV coordinates are not exported. I do texture mapping by this line of code in vertexshaderfunction output.UV input.UV When I use BasicEffect I have no problem and model appears correctly. How can I use "just" lightings in my custom effects? here is inside of my Model Using BasicEffect This is my code for drawing with or without BasicEffect inside of my draw() method Matrix baseWorld Matrix.CreateScale(Scale) Matrix.CreateFromYawPitchRoll(Rotation.Y, Rotation.X, Rotation.Z) Matrix.CreateTranslation(Position) foreach(ModelMesh mesh in Model.Meshes) Matrix localWorld ModelTransforms mesh.ParentBone.Index baseWorld foreach(ModelMeshPart part in mesh.MeshParts) Effect effect part.Effect if (effect is BasicEffect) ((BasicEffect)effect).World localWorld ((BasicEffect)effect).View View ((BasicEffect)effect).Projection Projection ((BasicEffect)effect).EnableDefaultLighting() else setEffectParameter(effect, "World", localWorld) setEffectParameter(effect, "View", View) setEffectParameter(effect, "Projection", Projection) setEffectParameter(effect, "CameraPosition", CameraPosition) mesh.Draw() setEffectParameter is another method that sets effect parameter if i use my custom effect. |
12 | Sprite detect background color I have read somewhere that sprites can detect the background color, but I don't remember where and how it's working. What I'm trying to do is just a function to detect if the sprite is on a special surface, that has a special color, instead of using collision dedection between objects. Help is preciated! Thanks! |
12 | Drawing an arrow cursor on user dragging in XNA MonoGame I am writing a touch enabled game in MonoGame (XNA like API) and would like to display a an arrow 'cursor' as user is making a drag gesture from point A to point B. I am not sure on how to correctly approach this problem. It seems that its best to just draw a sprite from A to B and scale it as required. This would however mean it gets stretched as user continues dragging gesture in one direction. Or maybe its better to dynamically render the arrow so it looks better? |
12 | Creating a gradient for a texture Why is the color becoming dark on one side? Updated While debugging I looked at the lerp and it was calculating into a negative number at the start. So I added in checks for to low or high a value, and that seems to have fixed it. I'll answer the question myself unless someone can find a way to fix the formula that calculates the lerp, since that seems to be the culprit. My fix was this double lerp (start here) (start end) if (lerp lt 0d) lerp 0d if (lerp gt 1d) lerp 1d Original Question I'm applying a gradient to a texture per the answer in this topic Code to generate a color gradient within a texture using a diagonal line My code is referenced below. The code was seeming to work fine. I was using a two color gradient green to purple. However, when I changed it to two colors that blended well into a 3rd color, I could instantly see that something was wrong. For example, blue to purple was producing a red element outside of the gradient area. If you also look closely, the blue itself is also enhanced on the outer edges. It's almost as if the two colors are mixing outside of the gradient area, when they should be the original colors. Calling Code This is applying to the center of an area 80x25. Color colors new Color Color.Blue, Color.Purple float colorStops new float 0f, 1f Algorithms.GradientFill(new Point(40, 12), 3, 33, new Rectangle(0, 0, CellData.Width, CellData.Height), colors, colorStops) Gradient Calculation Code public static void GradientFill(Point position, int strength, int angle, Rectangle area, Color colors, float colorStops) double radians angle Math.PI 180 Math.Atan2(x1 x2, y1 y2) Vector2 angleVector new Vector2((float)(Math.Sin(radians) strength), (float)(Math.Cos(radians) strength)) 2 Vector2 location new Vector2(position.X, position.Y) Vector2 endingPoint location angleVector Vector2 startingPoint location angleVector double x1 (startingPoint.X (double)area.Width) 2.0f 1.0f double y1 (startingPoint.Y (double)area.Height) 2.0f 1.0f double x2 (endingPoint.X (double)area.Width) 2.0f 1.0f double y2 (endingPoint.Y (double)area.Height) 2.0f 1.0f double start x1 angleVector.X y1 angleVector.Y double end x2 angleVector.X y2 angleVector.Y for (int x area.X x lt area.Width x ) for (int y area.Y y lt area.Height y ) but we need vectors from ( 1, 1) to (1, 1) instead of pixels from (0, 0) to (width, height) double u (x (double)area.Width) 2.0f 1.0f double v (y (double)area.Height) 2.0f 1.0f double here u angleVector.X v angleVector.Y double lerp (start here) (start end) float newLerp int counter for (counter 0 counter lt colorStops.Length amp amp colorStops counter lt (float)lerp counter ) counter counter Math.Max(counter, 0) counter Math.Min(counter, colorStops.Length 2) newLerp (colorStops counter (float)lerp) (colorStops counter colorStops counter 1 ) SetPixel(x, y, color) |
12 | Clarification on RenderTargetUsage in XNA 4.0 I'm trying to understand the exact meaning of RenderTargetUsage.DiscardContents. The documentation says Determines how render target data is used once a new render target is set. DiscardContents Always clears the render target data. Does calling GraphicsDevice.SetRenderTarget(null) to return to the back buffer count as setting a new render target (therefore clearing discarding any previous one)? Are the contents discarded either way at the end of the frame (i.e. when the graphic device presents), or do they persist into future frames even in this mode? |
12 | Sound effects in separate thread? Does it make sense to carry out all audio (music, sound effects, etc.) in a separate thread? In your experience, how large would you expect the performance impact of playing some MP3 music and 10 30 sound effects to be? Could performance be an issue with starting to play many different sound effects (e.g. in the same frame)? |
12 | best way to implement movement after A pathfinding? tile based movement vs pixel based? I was able to implement the A pathfinding algorithm to calculate a path from the enemy to player. After trying to do movement well, I realized I ran into all sorts of problems. I was able to add clearance to the pathfinding, so I'm now going to have sprites of variable size, which leads to even more issues. I am currently doing movement like path 0 is first Tile in path and it is removed when you get to it if (path.Count gt 0) if (path 0 .isTouching(this)) path.RemoveAt(0) if (path 0 .getCenterX() gt this.getCenterX()) speedX speed speedY 0 System.Console.WriteLine("moving right") else if (path 0 .getCenterX() lt this.getCenterX()) speedX speed speedY 0 System.Console.WriteLine("moving left") if (path 0 .getCenterY() gt this.getCenterY()) speedX 0 speedY speed System.Console.WriteLine("moving down") else if (path 0 .getCenterY() lt this.getCenterY()) speedX 0 speedY speed System.Console.WriteLine("moving up") this.move(speedX, speedY) This doesn't work very well for a variety of reasons. I am certain the pathfinding I implemented calculates the proper path of Tiles. Now I think I have to move from a pixel to pixel movement tile to tile in order to have this working better. This would probably help, right? How is movement usually done to work with A ? If the tile based movement would aid, any tips on implementing this? |
12 | how to move the camera behind a model with the same angle? in XNA I'm having difficulty moving my camera behind an object in a 3D world. I'd like to have two view modes for fps (first person). external view behind the character (third person). I've searched the net for examples but they don't work in my project. Here is my code used to change the view when F2 is pressed Camera double X1 this.camera.PositionX double X2 this.player.Position.X double Z1 this.camera.PositionZ double Z2 this.player.Position.Z Verify that the user must not let the press F2 if (!this.camera.IsF2TurnedInBoucle) If the view mode is the second person if (this.camera.ViewCamera type CameraSimples.ChangeView.SecondPerson) this.camera.ViewCamera type CameraSimples.ChangeView.firstPerson Calcul position ?? Here my problem double direction Math.Atan2(X2 X1, Z2 Z1) 180.0 3.14159265 Calcul angle ?? Here my problem this.camera.position .. this.camera.rotation .. this.camera.MouseRadian LeftrightRot (float)direction IF mode view is first person else .... |
12 | Creating installer for WinForms XNA with compiled content I have a Windows Forms application that uses a custom Graphics Device control based on Microsoft's "WinForms Series 1 Graphics Device" sample. The application makes use of a single model (the spaceship model included with the second sample) and its associated texture. My main project includes a reference to an XNA Game Library project, which contains a Content reference to my Content project. When I build and run the project in either Debug or Release configuration, my model and texture are compiled into XNB format and loaded into the application as expected. However, when I create an installer (either Windows Installer or ClickOnce) and run it, the content files are not present in any form in the installed location, so obviously I get a runtime exception. I've toggled every option I can find that looks relevant. Am I missing something? |
12 | Correct velocity on collision between two rects I have two moving objects. The objects consist of a velocity vector2, a Rectangle and a vector2 as position (origin in the middle of the rect). Some rough pseudo code for my collision checking function foreach (object1 in objects) foreach (object2 in objects) intersectionRect Rectangle.Intersect(object1.Rectangle, object2.Rectangle) if (intersectionRect ! Rectangle.Empty) If colliding ResolveCollision(object1, object2, intersectionRect) does nothing currently object1.position object1.velocity object2.position object2.velocity My problem now is how to do the collision resolution. I need help figuring out a formula to calculate the new velocities of the objects so that they only move as far as they need to not intersect anymore. I have used google to find a solution, but the most stuff I found was how to do collisions and not how to resolve them. |
12 | How do you create a .XNB Font file for use with CocosSharp? I know the .XNB file format is an XNA thing and that CocosSharp inherits this from its MonoGame roots. However there doesn't seem to be any information on how to create your own .XNB fonts to use with CocosSharp. I've tried searching but can find any information. Could someone explain it here or point me to a tutorial on how to create .XNB font file for use with CocosSharp? A site to download already compiled .XNB Fonts would also be acceptable. Update Another thing that makes this tricky is that I guess XNA Game Studio could be used, but it's not compatible with Windows 8.1 which is what I currently use for my dev machine... |
12 | Math behind XNA's spriteBatch.draw() color parameter? I'm trying to make a shader that changes the color of a sprite the way the XNA spriteBatch.draw() color parameter changes color. I don't know exactly what it is called (the closest word I can think of is 'tinting' but that's not right I don't think) and it's kind of hard to explain the way it looks. Say you set the parameter to 'Red' white pixels in the original texture would become completely red, while black pixels would remain black. Grey pixels would look dark red, blue pixels might look purple, green pixels might look brownish. If you set the parameter to 'Black' the texture would become completely black. Does anyone know the math behind this, or what this technique is called? It's probably very simple and I'm just not seeing it. Thanks! |
12 | Loss of texture detail in XNA (Banding 16 bit issue) I'm loading in a background texture for my game, it's not vert detailed, it's just there too add some variance. The problem is that there looks like a large reduction in detail. I've included images below so you can see what I'm talking about. What would cause this to happen and how can I get my detail back? More info Verticies are VertexPositionTexture Load method Texture2D.FromStream Effect BasicEffect Also the project is a Silverlight XNA mix Source Image Image from game Note the images don't match up completely but you should get the idea. |
12 | XNA with WPF or Winforms If you compare integration between WPF with XNA vs Winforms with XNA, what is the most suitable framework to integrate XNA framework with. |
12 | How to put an invisible marker on a model and refer to it in the game? I am using XNA C to load up 3ds Max models exported in FBX format. Is there some way to mark a specific point in the model like the pipe of a gun so I can just refer to it and place a bullet in there directly to make shooting look good? |
12 | Why is my client laggy despite 60 update packets a second? I am developing a small multiplayer game with XNA. It's a usual client server architecture I have a server and many clients communicating with it through UDP (via .NET's Socket class). These clients send data to the server (for example, the player's position) and the server handles it and decides what to do (send it to every other client or drop it). What's the most efficient "correct" way to send position of moving object from a client to a server? Currently, I send the client's ID and player position 60 times a second (XNA's default update rate) while a player is moving. When I see my own player on the screen, it moves very smoothly, but other don't, despite every client having the same update rate. What am I doing wrong? |
12 | How do I get an XNA 4.0 game to run on other machines? Whenever I try and run a game made in XNA 4.0 on a machine other than one used for development, it just won't run. I've followed the instructions here to ensure that all the dependencies are present. To be clear I've done the following Downloaded and installed the Microsoft .NET Framework 4 Client Profile. Downloaded and installed the Microsoft XNA Framework Redistributable 4.0. Made sure I am not using anything contained within GamerServices and XNA.Net. , my references are as follows Microsoft.Xna.Framework Microsoft.Xna.Framework.Avatar Microsoft.Xna.Framework.Game Microsoft.Xna.Framework.Graphics Microsoft.Xna.Framework.Storage Microsoft.Xna.Framework.Video Microsoft.Xna.Framework.Xact mscorlib System System.Core System.Windows.Forms System.Xml System.Xml.Linq I also followed the advice here to ensure the problem was not within the code itself. I've tried the follow methods to get it to run (on both Vista and 7) Use the built in publishing functionality. This results in an error saying that Microsoft.Xna.Input.Touch needs to be present in the GAC. I've tried adding Microsoft.Xna.Input.Touch to the references, and this does not fix the issue. Copy the XNA dll files locally. This results in an error message stating that Microsoft.Xna.Game.dll or one of its dependencies could not be located. Copy over everything contained in Release. This results in an Application X stopped working... or APPCRASH error message the second it starts. My code is never reached. Is there any way to get this to work? I've been trying to get this to work with the deadline looming, and it's been a source of unneeded stress. |
12 | How can I draw sprites in layers based on their Y position? I am trying to figure out the most efficient way to draw sprites in a way that they layer properly based on their Y position. Lets say I have four objects of the same class named A, B, C, and D, and they all must be drawn. Their respective Y positions are 12, 16, 13, and 17. If I draw A then B then C then D, they will draw and lay over the tops of each other in a weird manner. I want to draw them "largest y is closest." I know you could probably use a sort routine to sort them all based on Y, but I would imagine that would generate a huge amount of lag because of all the calculations, especially when you're needing to draw about fifty or sixty objects. What's the right way to go about drawing them? How would I modify this to include two different types of objects with similar properties (ie, "creatures" and "projectiles" ?) |
12 | 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. |
12 | Determining if a character is within the field of view in XNA I'm trying to creating a field of view for the camera I'm making for a game. It rotates around a circle for 180 degrees while the head moves accordingly. I'm going to bound the field of view within an isosceles triangle using the method described on this website. The problem I'm having is that I don't know how I'm going to detect if the field of view has intersected with the character as seen in this link. Any help with this would be greatly appreciated. EDIT sorry I meant an asset in game representing a camera much like the enemy in the second link, not an actual camera class in XNA(really sorry) |
12 | Creating a 2D perspective in 3D game I'm new to XNA and 3D game development in general. I'm creating a puzzle game kind of similar to tetris, built with blocks. I decided to build the game in 3D since I can do some cool animations and transitions when using 3D blocks with physics etc. However, I really do want the game to look "2D". My blocks are made up of 3D models, but I don't want that to be visible when they're not animating. I have followed some XNA tutorials and set up my scene like this this.view Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up) this.aspectRatio graphics.GraphicsDevice.Viewport.AspectRatio this.projection Matrix.CreatePerspectiveFieldOfView( MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f) ... and it gives me a very 3D ish look. For example, the blocks in the center of the screen looks exactly how I want them, but closer to the edges of the screen I can see the rotation and sides of them. My guess is that I'm not after a perspective field of view, but any help on which field of view settings to use to get a "flat" look when the blocks aren't rotated would be great! |
12 | Change emission level of a set of vertices within a mesh ok so here is the problem I need to solve. I have a known set of vertices that I need to "animate" the emission level of. Currently I have a vertex definition setup and RGB color data for each vertex. and I can animate that. but obviously that doesn't effect the lighting. what would be ideal I think is if I could take the basic effect class and apply it to just a few vertices at a time but so far I cant find a way to use it on anything less than a mesh. Update Thanks to Evan I think the way to go is to get each of these indices and create a mesh that will overlay the existing model. This would make it easier to control transparency as well as the emission. The question I have is lets say these indices do not make up a full triangle? Maybe after I find all of the vertices I also find that they don't divide out to 3. I guess what I need now is what would a good way to pull this mesh apart be? |
12 | 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. |
12 | XNA Seeing through heightmap problem I've recently started learning how to program in 3D with XNA and I've been trying to implement a Terrain3D class(a very simple height map). I've managed to draw a simple terrain, but I'm getting a weird bug where I can see through the terrain. This bug happens when I'm looking through a hill from the map. Here is a picture of what happens I was wondering if this is a common mistake for starters and if any of you ever experienced the same problem and could tell me what I'm doing wrong. If it's not such an obvious problem, here is my Draw method public override void Draw() Parent.Engine.SpriteBatch.Begin(SpriteBlendMode.None, SpriteSortMode.Immediate, SaveStateMode.SaveState) Camera3D cam (Camera3D)Parent.Engine.Services.GetService(typeof(Camera3D)) if (cam null) throw new Exception("Camera3D couldn't be found. Drawing a 3D terrain requires a 3D camera.") float triangleCount indices.Length 3f basicEffect.Begin() basicEffect.World worldMatrix basicEffect.View cam.ViewMatrix basicEffect.Projection cam.ProjectionMatrix basicEffect.VertexColorEnabled true Parent.Engine.GraphicsDevice.VertexDeclaration new VertexDeclaration( Parent.Engine.GraphicsDevice, VertexPositionColor.VertexElements) foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes) pass.Begin() Parent.Engine.GraphicsDevice.Vertices 0 .SetSource(vertexBuffer, 0, VertexPositionColor.SizeInBytes) Parent.Engine.GraphicsDevice.Indices indexBuffer Parent.Engine.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, vertices.Length, 0, (int)triangleCount) pass.End() basicEffect.End() Parent.Engine.SpriteBatch.End() Parent is just a property holding the screen that the component belongs to. Engine is a property of that parent screen holding the engine that it belongs to. If I should post more code(like the initialization code), then just leave a comment and I will. |
12 | CLR Profiler Allocated Bytes and XNA ContentManager I've been fighting with XNA ContentManager and memory allocations for some weeks because I'm trying to port my game from XNA (Windows) to ExEn Monotouch (iphone). The problem is that after playing a few levels, my game exits unexpectedly on a real iPhone device (not simulator). Profiling memory usage on Windows with CLRProfile, I found some useful stuff but I also found something I dont understand. If I use 2 ContentManagers (1 for shared assets and 1 for level assets), when profiling, "Allocated Bytes" grows and grows after level through level but Memory consumption measured by Windows Task Manager stays constant (down when I unload the content manager and up again when I load content). Obviously, I contentManager.Unload() when level ends. After a few levels my game exits unexpectedly on an iPhone device. If I use 1 content manager, "CRLProfiler Allocated Bytes" stays constant on Windows and on the iPhone I can play the game normally and it doesnt exit unexpectedly. I use the same assets level through level. It seems like in ios (iPhone) when loading and unloading the same assets, it allocates memory and consumes all device memory, so the ios kill it. Can anybody explain me how this really works? I've read quite a bit, but I still don't understand what's going on. |
12 | How can I create the correct player object based on a type in a network message? I am using lidgren as a networking library for a small XNA game. I am using a client server architecture for the game. Currently, I have the client and server connecting but I would like to be able to pass an enum with a character type when the client requests to join the server. Here is a sample of my code while ((inMsg networkManager.ReadMessage()) ! null) switch (inMsg.MessageType) case NetIncomingMessageType.StatusChanged switch ((NetConnectionStatus)inMsg.ReadByte()) case NetConnectionStatus.Connected if (!this.isHosting) Extract player info from message and create a local player break case NetConnectionStatus.RespondedAwaitingApproval pType (PlayerType)inMsg.ReadByte() playerManager.AddPlayer(pType) Then I will send the player information to the client inMsg.SenderConnection.Approve() break break this.networkManager.Recycle(inMsg) When server gets a message with RespondedAwaitingApproval flag, I would like to be able to read the message, extract the type and create an instance of a player of that type. How can I accomplish that? |
12 | Grid based collision How many cells? The game I'm creating is a bullet hell game, so there can be quite a few objects on the screen at any given time. It probably maxes out at about 40 enemies and 200 or so bullets. That being said, I'm splitting up the playing field into a grid for my collision checking. Right now, it's only 8 cells. How many would be optimal? I'm worried that if I use too many, I'll be wasting CPU power. My main concern is processing power, to make the game run smoothly. RAM is not a big concern for me. |
12 | XNA Obtaining depth from the scene's render target? Possible Duplicate Depth buffer and render target I'm currently rendering my scene to a render target so it can be used for rendering methods such as post processing and order independent transparency. rtScene new RenderTarget2D( GraphicsDevice, GraphicsDevice.PresentationParameters.BackBufferWidth, GraphicsDevice.PresentationParameters.BackBufferHeight, false, SurfaceFormat.Rgba64, DepthFormat.Depth24Stencil8, Requires a depth format for objects to be drawn correctly (e.g. wireframe model surrounding model) 0, RenderTargetUsage.PreserveContents ) I am required to use RenderTargetUsage.PreserveContents so that the same render target can be rendered to multiple times, once for each of the draw methods below. DrawBackground DrawDeferred DrawForward DrawTransparent The problem is that DrawTransparent requires a copy of the scene's depth as a texture. Is there any way to obtain this from the scene render target above (rtScene)? I can't have more than one render target with RenderTargetUsage.PreserveContents as this causes problems on hardware such as the XBOX 360, so rendering the depth to a separate render target at the same time as I render the scene isn't possible as far as I can tell. Would I be able to get around this problem by "Ping Ponging" two render targets (using the more compatible RenderTargetUsage.DiscardContents) and using the result for the depth texture? |
12 | At this point in time, avoid XNA? XNA seemed like a valid option a few years ago, but XNA was never a real success, and now it seems like a footnote, even Microsoft seems to treat it that way. Should I just go the DirectX route instead? Ideally, eventually, I'd like my games to be playable on all major platforms (Windows, Linux, Mac all consoles), but my primary focus is getting the games out the door on Windows XP, 7 and 8. EDIT This question and releated might already be answered here What is the future of XNA in Windows 8 or how will managed games be developed in Windows 8? |
12 | Why would a Bounding Sphere and BoundingBox not intersect (when they should)? I have a bounding sphere and a bounding box that should be intersecting, however, Intersects(...) is returning false. For example, the following returns false new BoundingSphere(new Vector3(500, 105, 0), 25).Intersects( new BoundingBox(new Vector3(466,219,0), new Vector3(519,26,0)) ) |
12 | How to create a view looking down the sight of the gun I am in the midst of creating an FPS game using XNA. I am using the camera class from the First Person camera demo from dhpoware.com, and everything is working great. What I'd like to implement is the ability to press the right mouse click and then the view changes so that you look down the gun, like the following image I have searched and searched but haven't found anything that will help me out, or at least point me in the right direction. Can anyone help? |
12 | XNA for multiplayer game? I've made a few games without using XNA and recently started to see some documents and samples around and took an interest on it but i have a few doubts for going into it or not. What limitations do i have if i am planning to create a mmorpg with XNA for distributing it (if it has a item mall or is paid to play for example) ? Do i need more accounts to test it (for example to login into my own game 3 players) or XNA does not cost anything at this level (heard something about LIVE Gold Membership plus which is why i am asking this one) ? |
12 | 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 |
12 | In which software do the professional game developers create 3D Model? I am just thinking about beginning game development in xna c . However, I don't know (and no tutorial teaches) how do professional game developers create a 3D Model Scene. How can we create a realistic looking model and what is the hardware configuration needed in machine for using such a software? |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.