_id
int64
0
49
text
stringlengths
71
4.19k
12
Time Required for Animation to Finish Using a tutorial found on the AppHub, I've been attempted to add controls to a sample sprite sheet. I am able to get all the animations working, but for stuff like punching or stabbing, the animations require a timer to stop them from playing repeatedly. XNA uses a default framerate of 60, but I have the animations running at 10 FPS using the following code int punchIndex walk.GetIndex("obj Walk000") punchIndex (int)(time animationFPS) punchFC batch.Draw(punch.Texture, position, punch.SourceRectangle(punchIndex), Color.White, rotation, origin, 1.0f, SpriteEffects.FlipHorizontally, 1.0f) break Where animationFPS 10 and punchFC is 6, which is the number of frames in the animation. Using this data, I have calculated a required time of 0.5 seconds for the animation to complete, but that seems to be incorrect, so I'm looking for someone to show me how to do the math properly.
12
Adjust treble and bass on Audio in XNA I am trying to "muffle" the sounds that are being played in my game and the best way I can think of doing this, is by lowering the treble of the sound. I have looked through all the members of the Song SoundEffect SoundEffectInstance classes and I cannot find a way to alter the sounds. How can I accomplish this?
12
Some questions about lists I've been looking for articles or tutorials on this and I can't seem to find any, so I thought I'd ask here. I've created a bullet class in my game that is added and removed through a list. If I'm going to make these bullets work the way I want them to I need to be able to do two things One, I need to check if the bullets are colliding with each other and then remove the two bullets that are colliding. I've tried doing it by updating the bullet list with a for statement and then checking for collision with another for statement, but that occasionally crashes the game. Two, I need to be able to check how far away every other bullet in the list is from the current one. So how can I go about doing this?
12
Rotation based on movement How can i calculate angle based on movement in C XNA when i'm moving object with accelerometer? If object is moving up, sprite would rotate in corresponding direction. Should i use two vector coordinates(old, new) to calculate angle using Atan2?
12
rendering a spritebatch to a temporary buffer and then offset that to the main screen I've been trying to figure out how to do this but I have a bunch of screens, each with their own Draw method. However, I'd like to render all sprites offset by the screen position without altering their locations before I do the drawing. So, if I render a sprite on a screen at 0,0 but the screen itself is offset to 50,50 it still renders to a window position of 0,0 instead of to the window position of 50,50. I've been thinking about rendering each screen to their own texture and then rendering that texture to the main spriteBatch but reading another question you could lose a lot of information such as alpha transparency Any help will be appreciated to get me on the right path. Thanks. Update Also I'd prefer it to be recursive so that screens within screens are also offset appropriately.
12
Getting BEPUphysics to draw its entities Isn't there a way, to force BEPUphsyics to show what it is doing? I am here with my existing XNA project, starting to put in BEPUphysics, but I am not seeing what it is doing. Take my model for instance. I think I made a StaticMesh here public BEPUphysics.Collidables.StaticMesh PhysicsMesh public Space space private Hero hero public override void LoadContent() ... space new Space() Vector3 vertices int indices TriangleMesh.GetVerticesAndIndicesFromModel( model.getCoreModel(), out vertices, out indices) PhysicsMesh new BEPUphysics.Collidables.StaticMesh(vertices, indices, new AffineTransform(new Vector3(0, 40, 0))) space.Add( hero.PhysicsMesh) space.ForceUpdater.Gravity new Vector3(0, 9.81f, 0) That's the only thing I made BEPU Wise in my game. All other models don't have physics attached to them. But, like I said. I see nothing when the game is running. Only my model, not falling, not doing anything. I would like to see the full thing BEPU is doing in runtime.
12
Does passing uniform constants from technique into shader cause branches? I am trying to find a way to organize my evergrowing number of shader techniques functions (I am coding in sm 3.0). One way is to do this float4 PS Crossroads(PS INPUT input, uniform bool left right) COLOR0 if (left right) GoLeft() else GoRight() ... technique LEFT pass Pass1 VertexShader compile vs 3 0 VertSh() PixelShader compile ps 3 0 PS Crossroads(true) technique RIGHT pass Pass1 VertexShader compile vs 3 0 VertSh() PixelShader compile ps 3 0 PS Crossroads(false) My question is will this cause a branch at runtime or will the compiler be smart enough to split it into two separate techniques? Thanks. P.S. Ok I won't post this as answer, because we already have an answer by someone much more experienced than me, but from my humble tests (on different PCs) and my humble Google research, this approach (using uniform constants) is efficient and indeed forces the compiler to create different shader versions for each branch, removing flow controll completely from the finall compiled shader. I tested the compiled shader codes with Nvidia NSight.
12
How do I detect and remove completed rows of blocks in Tetris? I am making Tetris for a learning experience in XNA, and I'm having trouble deleted completed rows. I am having an issue with deleting rows, for some reason when I go to delete a row, I end up creating more blocks or not deleting all of the blocks in the row. The method I am using to detect and remove blocks is as follows 'rowCount' is an int 20 holding the number of blocks in each row (my playing field is 20 rows tall and 10 blocks wide). for (int i 0 i lt rowCount.Length i ) if (rowCount i gt 10) The row is full, remove the blocks. 'blocks' is a list of all blocks that have settled. for (int j 0 j lt blocks.Count j ) if (blocks j .Row i) If the settled block is in this row, remove it. blocks.RemoveAt(j) rowCount i Move any blocks above the now empty row down one row. foreach (Block b in blocks) if (b.Row lt i) b.Row rowCount b.Row This is done in my main Update method after I've determined if the current block has settled or not. As implemented, this algorithm will usually end up recording more than ten blocks in some rows and will not correctly clear completed rows and move the rows above down one unit. Why is this, and what can I do to fix the algorithm?
12
Min Max of two vectors? This seems like a simple question, but i'm having trouble searching the internet for it. In XNA, during a collision detecting method, I would determin the minimum of some vectors. Get the minimum top point Vector2 minTopPoint1 Vector2.Min(topLeft1, topRight1) Get the minimum bottom point Vector2 minBottomPoint1 Vector2.Min(bottomLeft1, bottomRight1) Get the minimum of both the top and bottom points. Vector2 minPoint1 Vector2.Min(minTopPoint1, minBottomPoint1) I switched over to making a C engine, and am trying to replicate the collision formula (Honestly, it's confusing enough, I just need to replicate it from XNA) I made my own Vector2, and now I need to make this Min function. So, what is the minimum or maximum of two vectors? Is it just the magnitude of the two vectors measured against eatchother? Is it the x and y values min maxed somehow?
12
How to render depthmap image in 3d? I'm new to game development and XNA. I have this depthmap image and I want to render it in 3D, how do I do it, any tutorial or blog post would be helpful.
12
Map state in XNA on WP8 I am developing an RPG for Windows Phone 8 using XNA. I have a map screen and a fight screen. I want to use XNA for both to utilize the graphics helpers and because XNA is awesome. My question is, how do I save the map state between the two screens? That is , how do I save the location of the PC and the enemies when I travel back and forth between the two screens?
12
What is the point of the XNA.Input.Button enum? I am trying to make an InputManager class that will let me basically bridge XNA's various input methods and do a corresponding action in my game. Part of this is designing different keybindings. Suppose I have a class GamePadBinding InputBinding lt Button gt this is the Button enum from XNA.Input and has a variety of different buttons (Left, A, etc). However, to actually check input, I have to call something like if (GamePad.GetState(PlayerIndex.One).DPad.Left ButtonState.Pressed), and the problem with that is that it uses a struct with readonly values. How am I expected to store an enum of type Button and compare that with this? I really am not seeing the point of this enum.
12
XNA C How can I prevent blurring when drawing from a RenderTarget2D? I'm making a game and I want the end graphics to look chunky and pixellated, so I'm drawing from the spritebatch onto a RenderTarget2D which is 1 4th the size of the actual backbuffer, and then drawing from that to the backbuffer. At first the sprites were blurred by antialiasing and I read that using SamplerState.PointWrap in the spritebatch Begin call would ease this a bit so I made that change. Everything seemed better, however the final on screen image is still blurry and I think this is because of how it draws from the rendertarget2D to the backbuffer. The image here is a comparison On the left is how the output looks now and the right is how I want it to look.
12
Collision detections too fast? I'm creating a simple asteroids game and I have three lists with big asteroids, small asteroids and missiles. When the player hits a big asteroid two small asteroids are created. But The problem is that for the most of the time, the two small asteroids never get time to show up! It seems like the missile hits them too, despite that I remove the missile from the list, before the small asteroids are created. The code below is from my object manager. What is wrong and how can I improve my code to avoid this? Check if missile hit big asteroid public void CollisionControlMissileHitAsteroidBig(ContentManager content) for (int i 0 i lt missilesList.Count() i ) for (int ii 0 ii lt asteroidsBigList.Count() ii ) if (missilesList.ElementAt(i).Bounds().Intersects(asteroidsBigList.ElementAt(ii).Bounds())) missilesList.RemoveAt(i) for(int x 0 x lt 2 x ) AddNewSmallAsteroidToList(new AsteroidSmall(content, asteroidsBigList.ElementAt(ii).Position)) asteroidsBigList.RemoveAt(ii) i ii Check if missile hit small asteroid public void CollisionControlMissileHitAsteroidSmall() for (int i 0 i lt missilesList.Count() i ) for (int ii 0 ii lt asteroidsSmallList.Count() ii ) if (missilesList.ElementAt(i).Bounds().Intersects(asteroidsSmallList.ElementAt(ii).Bounds())) missilesList.RemoveAt(i) asteroidsSmallList.RemoveAt(ii) i ii EDIT I'm not sure I have done right? There are some problems, the big asteroids is still on the screen and then I guess the missile is still there to, because when two new small asteroids are created, most of the time there is only one, which I think is because it collide with the old missile? That's why I removed the missile from the list before I created the new small asteroids. More help is appreciated! public void CollisionControlMissileHitAsteroidBig(ContentManager content) for (int i 0 i lt missilesList.Count() i ) for (int ii 0 ii lt asteroidsBigList.Count() ii ) if (missilesList.ElementAt(i).Bounds().Intersects(asteroidsBigList.ElementAt(ii).Bounds())) missilesList.RemoveAt(i) for(int x 0 x lt 2 x ) AddNewSmallAsteroidToList(new AsteroidSmall(content, asteroidsBigList.ElementAt(ii).Position)) asteroidsBigListRemove.Add(asteroidsBigList.ElementAt(ii)) missilesListRemove.Add(missilesList.ElementAt(i)) asteroidsBigListRemove.Clear() missilesListRemove.Clear()
12
How to rotate an object towards the walking direction? I'm working on a game where you move a object on a game surface of cells, every time you move this object it steps to a cell, up, down, left or to the right. I have been trying to find out a way to rotate the object soo it is facing the moving direction. The rotation should be 90 degrees. It's one thing if the object is going from Up to Left and then rotate it 90 degrees, but what if object is going from Up to Down, then it need to rotate 180 degrees. I need some help with this issue to solve this in a simple and good way? Thanks! This is the code for moving upwards and the other moving directions are similar. I'm using a short delay, so that the player can't move to fast on the game surface. Upp public void Up() if (milliSeconds1 gt walkingTimer) Position new Vector2(Position.X, Position.Y walkingSpeed) milliSeconds1 0 And in the Update Position Position Direction 1 EDIT I solved this by myself! I just used radian values for each directions! )
12
How should I handle shared classes between the Game project and the Content Extension Library? I've been using XNA for a while but recently I've needed to write a content extension library which I haven't done before. I need to import a TextureAtlas class from a file that is exported by a tool I wrote. The output of my editor is a serialized XML file that contains a list of all StaticImages and Animations in the TextureAtlasFile class that its serialized from. In my solution I have the TextureAtlasContentLoader project which holds all of the classes that I will need for the texture atlas both in game and for loading the actual content. The importer deserializes the xml back to a TextureAtlasFile and the processor converts it to a TextureAtlas to return after it is loaded. The problem is that I have no idea how to share the classes between the content extension project and the game project that will be using the TextureAtlas class. I've tried referencing the content extension project in the game project and that works fine to get me pass compiling but it throws a ContentLoadException exception when I call textures Game1.content.Load lt TextureAtlas gt ("MainMenu") saying Error loading "MainMenu". Cannot find type Client.Render.TextureAtlas, TextureAtlasContentLoader, Version 1.0.0.0, Culture neutral, PublicKeyToken null. The only other clue to whats wrong I have is a warning while compiling that says Warning 2 The referenced assembly "Microsoft.Xna.Framework.Content.Pipeline, Version 4.0.0.0, Culture neutral, PublicKeyToken 842cf8be1de50553, processorArchitecture x86" could not be resolved because it has a dependency on "Microsoft.Build.Framework, Version 4.0.0.0, Culture neutral, PublicKeyToken b03f5f7f11d50a3a" which is not in the currently targeted framework ".NETFramework,Version v4.0,Profile Client". Please remove references to assemblies not in the targeted framework or consider retargeting your project. Client which leads me to believe I'm not supposed to reference it in the game project. So to summarize my question, how do I handle my TextureAtlas and TextureHandle class that both the content loader and the game project need without causing errors?
12
Sweep collision between two moving spheres? Say I have a scenario like this Here I got two spheres (sphere A and B) that moves from on spot to another during a frame. How can I predict where these two collide if they collide at all? In between these frames? I tried to look it up and found this page, but I didn't understand much of it. Could someone try to explain this to me? I'm coding this in C with XNA and I've been stuck with this issue for a very long time now
12
Decompile an FX shader Is it possible to decompile a .xnb file? I've lost my shader code, but only have my .xnb file left.
12
How can I draw the inside of a box as well as the outside? I have a 3D box in which I have some holes. The thing is that when I look through the holes, I can't see the wall of the box that should appear as the inner wall. How can I draw this as well?
12
How to sync the actions in a mutiplayer game? I connect the clients with UDP (its a peer to peer connection on a multicast network) and the clients are sending their positions in every frame (in WP7 it means the default 30 FPS) to each other. This game is kinda a pong game, and my problem is the next whenever the opponent hits the ball the angle will not be the same on both mobiles. I think its because the latency (1 pixel difference can cause a different angle). So my question is how can I sync the hitting event?
12
How can I render a model on top of another model regardless of their relative Z positions? I was wondering if there's any way to render models over other 3D models regardless of their relative positions? Kind of like how it works in 2D graphics, you set a render order and it renders them based on that instead of taking the depth and figuring out which is in front of which.
12
Building 2D Assets for a Game Targeting Multiple Framerates To make a real world example, lets assume I want to build an animated sprite for an explosion. The duration of the animation should last 1 second, and we'll say exactly one second to make the math a bit more simple. And lets assume I'm using XNA and my goal is to target both XBox (60fps), PC (60fps), and Windows Phone 7 (30fps). My question is this, how should I build the sprite animations so that my programming is as simple as possible without simply using a timer to calculate which frame I should be on (which I feel would make the animation "choppy")?
12
For a 2D XNA game, should I use the built in Vector2 or Vector3 or port my own class from ActionScript? I use a lot of 2D vectors in my Flash games basically all velocities, positions etc I store in this way. My Vector2D class has lots of built in functions for rotation, dotproduct, projectOnto etc. The native Vector2 class doesn't seem to have half of this stuff, but it is used in a lot of places. The Vector3 has all this stuff, but has an extra dimension I don't need. So should I use either of the built in ones or port my AS3 class? Or should I try to extend Vector2 and add the extra functionality I need. Could that cause any problems?
12
Assigning bone transform in every draw a good idea? In my Draw method, I am doing the following thisMesh.CopyAbsoluteBoneTransformsTo(transforms) Is this a good idea? Or should I do this once at the constructor level?
12
How to make a world to player inventory system? I am running into an issue of trying to implement an inventory system within XNA (doesn't really matter, could be any platform) but so far. Here is the issue I am trying to wrap my head around How can I get an item from the world (think when you kill a monster it drops armor) and get it into my player's inventory? If an inventory is just a list of items, technically, how could I get Steel Sword from the world into my player's inventory without having a class do more than one thing? I currently have an item struct, which contains a unique hex value, a count of how many items there are (for stackables, like arrows) and a Texture for rendering within the inventory, and some other unimportant properties (name, description, etc). It would be bad design if I had to modify my existing item class to house a world position, along with collision detection (don't want the item falling through the earth). Thanks for any considerations!
12
XNA Content Loading works on my machine but not others I'm using XNAWinForm series 2 from App Hub for some task that needs 3d rendering. It works fine on my PC, but I have problems in running this code on other machines. I installed XNA framework redistributable on that machine, I tried 32 and 64bit computers and still its not working. Even the code on app hub is not working on other machines. What should I do?
12
Keeping per client data, when using singleton based states In my game, I deal with a lot of units. Every unit implements a state machine, and changes states quite often. As a result, I'd like to keep my states as singletons, since I want to avoid the creation of one and the same state over and over again. This works quite OK for most case, except when I need to introduce some time intervals, e.g. in 5 seconds the unit has do something. Of course, everyone knows that singletons cannot keep per client data, which is exactly what I want to achieve. The state should be aware of the time elapsed since it was initiated for a specific unit. One way to do this would be to keep timers within the units themselves, but that doesn't make a good abstraction. Another one, which I am currently working on, is to keep the per client state, i.e. timers on a Dictionary Hash within the state. When a client initiates the state, the timer gets activated, and a dictionary record gets set. Every time when the specific timer is needed, the dictionary is queried with the id of the specific client. Then on state exit, the record is deleted. Which is in general the proper way to deal with these problems?
12
How to I create a resource manager? Currently I'm using XNA's ContentManager to load my content. For the unfamiliar the ContentManager deserializes classes from disk and keeps a reference for future requests. I'm currently facing a problem with management, where for some resources I don't want to deserialize them repeatedly (e.g. a texture) but for others I do (e.g. destructible level geometry). As it is now when I replay a level I get back the original class with the player's changes. For this reason I decided to inherit from ContentManager to provide some way of re deserializing a resource to get a new copy (probably using the protected ReadAsset lt T gt method). Now I'm thinking about how I should manage this. Ideally I want some way of saying you can re use Textures, but not Levels (i.e. when a Level is requested it always deserializes a new instance). While I think about that I'd also like to create my custom ContentManager with a view to get other niceties such as automatic unloading, on demand or in advance loading of assets, pre loaded place holder assets etc. How is this sort of class typically designed and how can I overcome my immediate problem (reloading particular types and re using instances of others)?
12
vertices, better to have more but draw a smaller area or less but expand a larger area I have a simple question really. I am creating water for a game and had two different design approaches Make a single plane that expands the entire playspace, which would take 6 vertices but cover a much larger area. The idea being the plane would be at a certain height so the sourrong land if higher should cover it. Check at regular intervals around the created land, ask if the height of that peice of land is below a certain height if so, draw a small square to cover the area and then check the next interval and the next... The idea being you'd have a lot more vertices but much less area will be drawn. Any help would be appreciated as to which design approach makes more sense.
12
Issues upscaling pixel art with SampleState.PointClamp I'm developing a 2D game, and I'm striving to create a nice blocky low res appearance for the game, yet allow it to be played at variable resolutions. So, I've researched resolution independency and have a nice system in place to have my game rendered at 640x480 to a RenderTarget2D, and then have the RenderTarget blown up on the back buffer. Anybody that's looked into this knows that by default scaled images will be antialiased, and to disable that, change the SampleState to PointClamp. So, I've done that, but now I'm having this issue where my sprites aren't upscaling properly. Certain pixels are becoming particularly chunky where they shouldn't be, and I'm not sure what the cause of this behavior is, and I haven't been able to find any documentation of anybody else having this issue, can anybody offer any insight? The last image illustrates the image rendered in game at 2X the original size. A 2 1 ratio should be a pretty straightforward scale to render, but if you look closely, there are some pixels that are at half size the others. Edit 2 Here's some code regarding the scaling. First, the game is captured by the render target at 640x480 resolution, then it is drawn at the back buffer's resolution (in the second image, reslution is 800x600, in the third image, resolution is 1280x960, I haven't messed with alternate aspect ratios yet). graphicsDevice.SetRenderTarget(RenderTarget) spriteBatch.Begin() spriteBatch.Draw(Texture, new Rectangle((int)location.X, (int)location.Y, frameWidth, frameHeight), new Rectangle((int)spriteLocation.X, (int)spriteLocation.Y, spriteWidth, spriteHeight, Color.White, 0f, Vector2.Zero, effect, .826f) spriteBatch.End() graphicsDevice.SetRenderTarget(null) spriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.PointClamp, null, null) spriteBatch.Draw(RenderTarget, new Rectangle(0,0, backbufferWidth, backbufferHeight), Color.White) spriteBatch.End() Edit 3 Code involving the sprite's height and width. First, in the class that my monster inherits from, is this little method that runs in the base class' Update() method. It just makes sure that if I have animations with non uniform sizes, that the sizes are updating properly. protected void UpdateFrameSizes() frameWidth animations currentAnimation .Frames animations currentAnimation .currentFrame .SizeAndsource.Width frameHeight animations currentAnimation .Frames animations currentAnimation .currentFrame .SizeAndsource.Height Then, just to make sure that the Width and Height were correct in his animation class, I checked those idleFrame1 new AnimationFrame(Texture, new Rectangle(154 0, 107 0, 154, 107), 1f) idleFrame2 new AnimationFrame(Texture, new Rectangle(154 1, 107 0, 154, 107), 1f) idleFrame3 new AnimationFrame(Texture, new Rectangle(154 2, 107 0, 154, 107), 1f) All looks correct here, I even went to the source image and counted the pixels (Yes, I know, his sprite sheet's dimensions are weird, but they're accurate). And then this data is all used in Edit 2's code snippet during the draw method.
12
Supporting Multiple Input Devices I'm currently developing a PC game with the assistance of XNA and I'm integrating keyboard and gamepad control support. Up until now I've only supported gamepad control, and finding an elegant way to allow the player to choose one or the other is posing a complicated task to resolve. I was thinking of creating a class that would sort of convert either input into a universal sort of data that the game could then use for the player's character and the rest of the game to interpret. Then, I thought maybe it would be simpler to create a duplicate of my main character's class, except to accept keyboard input instead of the gamepad input. Can anybody offer any insight?
12
(XNA) What's a Good Database Program for a Turn Based RPG? I'll begin by saying that I feel my level of expertise matters here, and so I have about a year worth of experience as a programmer in the C language and most of the .NET framework as a whole, but have scarcely worked with databases at all throughout my career so far. Can't exactly say why. Either way, I'm a bit of a beginner, although SQL LINQ I am capable of working with once I have this question resolved. Moving on... At home, I am developing a single player (so only one person needs to access it) turn based RPG in XNA. I have a lot of the logic done and the time has come for me to begin building a database for it. THE REQUIREMENTS There will be both dynamically written data not included with the program (such as the location in the world at which a player saved his game, that he may load in the same place) and read data that needs to be capable of being distributed easily with the program (such as a table containing stats of every monster). THE DESIRED BUT OPTIONAL PERKS Beyond these absolute requirements, ease of use is a second priority I want to focus on. My amatuer nature doesn't want me digging around on ground I am too unfamiliar with. MY ATTEMPTS AT RESEARCH I understand Access to be a simple to use (though oft frowned upon) choice that could work based on needing only one user to access the database at a time. SQL Server could also work, but I understand it to be more difficult to use based on my needs. And in both cases, I am not sure if there are complications associated with the distrubution of pre loaded data with the programs. In this case, I think I should use an XML file to hold the data I want the game to come with, but I am not sure. Amidst all of this, I have also considered creating the .dbml right there in Visual Studio because it seems the simplest, but same issue I don't know the limitations of capability and distribution. I have tried to outline what I know and what I need to accomplish, as well as some of the options I have attempted to research, but ultimately, my knowledge has holes in it I can't find the answers to and I can't form a conclusive answer. Thus, I ask you kind people, based on the above, what is my best option for how to start building my game's database?
12
How do I get bullets to move in the direction of the mouse's position? Possible Duplicate Shoot a bullet towards cursor top down 2d I'm creating a 2D top down shooter, and I want to get the bullets to go in the direction of the mouse. Not sure of the logic that goes into it.
12
Using components in the XNA Game State Management example? In the game state management example at the App Hub, they say that if you want to use components in the example you can extend the GameScreen to host other components inside itself. I'm having a very hard time trying to tie this up. I tried extending the GameScreen class by adding a public property of public List lt DrawableGameCompnent gt components get set and then add my components to that list when I initialize the current screen as well as looping over the components in the LoadContent, Update and Draw methods. However, this doesn't feel like the correct way to go mainly because it doesn't work when I get to the implementation of my GameplayScreen. Any thoughts?
12
Outlining external edges on a complex shape made of cubes? A gallery of my problem can be found here. I had to do it this way as it won't let me post more than 2 links due to my reputation. I'm trying to use 3D cubes to generate an isometric cube world. I got that working great and I merge only the visible vertices indices into a buffer and draw from that. Only problem is, as with any isometric game, it becomes difficult to differentiate between heights. For example in the first image this archways top merges with the cubes below. I ended up finding this shader and got it working by using it against a rendered normal map (second image) of the cubes. You may be able to guess my problem from that image. The final result looks like the third image. The back edges are not draw with an outline, which are the most important. Which based on the normal map also means that diagonals also have the same problem on their sides (fourth image). Is there any solution I can do for this? Either in the shader itself or perhaps when calculating the normals? I almost need to add something to the normal to distinguish their depth height so faces on similar planes don't merge on edge detection. Or maybe there's a totally different option I could use. Ideally I was aiming more for only edges to the air to be outlined so the archways bottom edges would not be outlined like they are now
12
How would I achieve diablo like 2D isometric projection? I am in the process of coming up with an idea for a game, and I would like it to be isometric like Diablo. The problem is I have no idea how it achieves the effect of height like in the following screenshot (on the columns) Whatever the case, I'm sure it is going to be harder to achieve then creating a traditional isometric game, but any ideas regarding the topic would be greatly appreciated.
12
Keep 3d model facing the camera at all angles I'm trying to keep a 3d plane facing the camera at all angles but while i have some success with this Vector3 gunToCam cam.cameraPosition getWorld.Translation Vector3 beamRight Vector3.Cross(torpDirection, gunToCam) beamRight.Normalize() Vector3 beamUp Vector3.Cross(beamRight, torpDirection) shipeffect.beamWorld Matrix.Identity shipeffect.beamWorld.Forward (torpDirection) 1f shipeffect.beamWorld.Right beamRight shipeffect.beamWorld.Up beamUp shipeffect.beamWorld.Translation shipeffect.beamPosition Note Logic not wrote by me i just found this rather useful It seems to only face the camera at certain angles. For example if i place the camera behind the plane you can see it that only Roll's around the axis like this http i.imgur.com FOKLx.png (imagine if you are looking from behind where you have fired from. Any idea what to what the problem is (angles are not my specialty) shipeffect is an object that holds this class variables public Texture2D altBeam public Model beam public Matrix beamWorld public Matrix gunTransforms public Vector3 beamPosition
12
3D Animations in XNA 3.1 Well, guys. I'm in a Game Design class at school. Before you ask "WHY ARE YOU USING 3.1 INSTEAD OF 4" I would like to point out that C 2008, and .NET framework 3 is NOT my preferred environment, nor is Blender 2.49. I have gotten a pretty decent grip on Blender so far, I think. At least, for what I've figured out how to do. ( Applying textures, exporting to .fbx, and bone weights ). Now, I've seen various mentions of using "Skinned Models" in xna 4.0, and I've noticed that 3.1 has no such distinction, so I assume anything you do in 4 with skinned models means alternative methods in 3.1. I have also found nearly NO documentation on 3.1. All of them seem to have actually been updated to cover 4.0 ( Seriously, since when do people update their outdated tutorials? ) I'm asking around to see if there's any way to play animations stored in .fbx files ( if so, how to do it ), so that I don't waste my time understanding the animations and what not in Blender. ( Or better yet, is there something else that I SHOULD be doing instead? ) If it's not achievable, then I can obviously just use a bunch of constants or some work around system to apply bone transformations, but it would be really nice if I didn't need to do that. Some other things I've noticed that ALL models I load seem to have semi transparent textures. Can anybody offer an immediate explanation for this? To see what I'm talking about, here's a video. Also, could somebody give me advice as far as loading an environment and multiple models? I think I would use the same camera and projection matrix, and then simply give a new "World" matrix to all of the items, but for some reason, I don't think that's quite right. I read somewhere that the purpose of the Matrix type was to avoid storing position information for every individual model, and store it collectively instead. ( Which, makes sense, really. Especially when some games probably load a gajillion models x3 Vector3's. That could add up fairly quickly, I'm sure. ) I know this is fairly generic vague, but since I haven't written any code with bugs, I can't exactly ask specific questions, I guess. If you have a resource that is still rele
12
Scroller game level map advice I'm started a XNA project to make a game similar in gameplay to Super Spy Hunter on a NES, which is used as a feature reference. The first thing I thought of is how to store and display level. Currently I'm thinking of using some tile graphics editor and custom pipeline for drawing level. I'm not sure however, that all is possible to implement every feature of reference game, but at least it's a start. Question is, looking at a given gameplay video, can you think of any possibly better approach then to design level using a tiles? By "better approach" I mean which will be either easier to work with, which will be more "natural" for this kind of game. The doubt comes mainly from a huge technology gap between then (1990) and now. So there is possibility that using current cpu power this could be done easier. Update 1. As I continue study reference game and ashes999 correctly mentioned procedural generation also comes into my mind. I began to think game logic is something like (simplified) while next road section exist get road section data set road generation options (borders type, road type, etc) set road section lenght while not end of a section generate road apply pseudorandom eye candy stuff this all looks like a pretty good data driven algorithm.
12
Keystone Correction using 3D Points of Kinect With XNA, I am displaying a simple rectangle which is projected onto the floor. The projector can be placed at an arbitrary position. Obviously, the projected rectangle gets distorted according to the projectors position and angle. A Kinect scans the floor looking for the four corners. Now my goal is to transform the original rectangle such that the projection is no longer distorted by basically pre warping the rectangle. My first approach was to do everything in 2D First compute a perspective transformation (using OpenCV's warpPerspective()) from the scanned points to the internal rectangle's points und apply the inverse to the rectangle. This seemed to work but was too slow as it couldn't be rendered on the GPU. The second approach was to do everything in 3D in order to use XNA's rendering features. First, I would display a plane, scan its corners with Kinect and map the received 3D Points to the original plane. Theoretically, I could apply the inverse of the perspective transformation to the plane, as I did in the 2D approach. However, since XNA works with a view and projection matrix, I can't just call a function such as warpPerspective() and get the desired result. I would need to compute the new parameters for the camera's view and projection matrix. Question Is it possible to compute these parameters and split them into two matrices (view and projection)? If not, is there another approach I could use?
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
Is there a way to write a camera class without matrix transformation? I have a problem with a camera class I got from the internet. It does a transformation like this public Matrix get transformation(GraphicsDevice graphicsDevice) transform Matrix.CreateTranslation(new Vector3( pos.X, pos.Y, 0)) Matrix.CreateRotationZ(Rotation) Matrix.CreateScale(new Vector3(Zoom, Zoom, 1)) Matrix.CreateTranslation(new Vector3(ViewportWidth 0.5f, ViewportHeight 0.5f, 0)) return transform Later the spritebatch is called like this spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, null, cam.get transformation(device)) The problem is that at this point the mouse coordinates are not relative anymore to the other sprites I draw. This is a problem because I try detect which sprite has been clicked. I understand that this issue can be solved by considering the following picture This was posted in a very good awnser before, here. But somehow this does not really help me. So my question is Is there a way to create a Camera class which does not use transformation, can be moved with keys and keeps the viewport coordinates relative? Thanks in advance!
12
2D terrain with midpoint displacement and collision I followed this theory Here to implement a simple scrolling 2D terrain for my running game. I am used to dealing with collision via a tile system but am looking for a good theory on how to perform terrain collision (keeping the player on top the land) with a midpoint displacement 2D terrain I am not worried about the physics aspect but how to determine if a character intersects an array of points generated by the theory above. Example if I have an array of points Points these points are used to draw lines to make a terrain. Now in my mind I would first find the player center. Take the center X and see which two points it is between. So if X is 4.6 lets say it is between points that lay on X 3 and X 6. Player X 4.6 Point1 X 3, Y 3 Point2 X 6, Y 5 So now knowing this I somehow need to calculate what Y would be giving that X 4.6. And once I have Y ensure that the Player Y CalculatedY. If it is not push the player up to what Y the player should be. So I guess what I a saying is X 3, Y 3 X 6, Y 5 X 4.6, Solve for Y
12
3D Procedural Planet Generation I was looking for some inspration for my Voxel based game I am writting and came across this http www.youtube.com watch?v rL8zDgTlXso. I would like to know how to go about (or preferably source examples) of how I would do that, in real time, and infinitley. In addition to that I was wondering how I would do this with a voxel based terrain? A procedural planet generator in 3D which constructs voxel data, my voxels are of the same size of thoose in minecraft. Any ideas? Edit I ported the simplex noise function i grok suggested written in C Python to C , I sure hope it works ) http pastebin.com TZSQwnye Edit 2 float noise(float x, float y, float z, float persistance, float amplitude, float frequency, float octaves) float total 0 for (int i 0 i lt octaves i ) frequency frequency i or frequency 2 ? amplitude amplitude i total total SimplexNoise.raw noise 3d(x frequency, y frequency, z frequency) amplitude return total
12
Simple collision detection for pong I'm making a simple pong game, and things are great so far, but I have an odd bug which causes my ball (well, it's a box really) to get stuck on occasion when detecting collision against the ceiling or floor. It looks as though it is trying to update too frequently to get out of the collision check. Basically the box slides against the top or bottom of the screen from one paddle to the other, and quickly bounces on and off the wall while doing so, but only bounces a few pixels from the wall. What can I do to avoid this problem? It seems to occur at random. Below is my collision detection for the wall, as well as my update method for the ball. public void UpdatePosition() size.X (int)position.X size.Y (int)position.Y position.X speed (float)Math.Cos(direction) position.Y speed (float)Math.Sin(direction) CheckWallHit() Checks for collision with the ceiling or floor. 2 Math.pi 360 degrees TODO Change collision so that ball bounces from wall after getting caught private void CheckWallHit() while (direction gt 2 Math.PI) direction 2 Math.PI while (direction lt 0) direction 2 Math.PI if (position.Y lt 0 (position.Y gt resetPos.Y 2 size.Height)) direction 2 Math.PI direction
12
2D graphics why use spritesheets? I have seen many examples of how to render sprites from a spritesheet but I havent grasped why it is the most common way of dealing with sprites in 2d games. I have started out with 2d sprite rendering in the few demo applications I've made by dealing with each animation frame for any given sprite type as its own texture and this collection of textures is stored in a dictionary. This seems to work for me, and suits my workflow pretty well, as I tend to make my animations as gif mng files and then extract the frames to individual pngs. Is there a noticeable performance advantage to rendering from a single sheet rather than from individual textures? With modern hardware that is capable of drawing millions of polygons to the screen a hundred times a second, does it even matter for my 2d games which just deal with a few dozen 50x100px rectangles? The implementation details of loading a texture into graphics memory and displaying it in XNA seems pretty abstracted. All I know is that textures are bound to the graphics device when they are loaded, then during the game loop, the textures get rendered in batches. So it's not clear to me whether my choice affects performance. I suspect that there are some very good reasons most 2d game developers seem to be using them, I just don't understand why.
12
Multiple ( V I ) Buffers, is it sane? Currently I am developing an RTS game using XNA ( ANX.Framework ). There is one thing bothers me. I am not sure in what way or how to organise Buffers. Should I use a new Vertexbuffer for any object ( e.g. a Char, a Table, an model ) or is it better to use ONE HUGE BIG Buffer to store any geometry in? I am still new to 3D Programming though I finished yet couple games using DirectX 9. Well, I hope this question qin't a duplicate and I appreciate any answer leading me into the right direction.
12
Best depth sorting method for a Top Down 2D game using a 3D physics engine I've spent many days googling this and still have issues with my game engine I'd like to ask about, which I haven't seen addressed before. I think the problem is that my game is an unusual combination of a completely 2D graphical approach using XNA's SpriteBatch, and a completely 3D engine (the amazing BEPU physics engine) with rotation mostly disabled. In essence, my question is similar to this one (the part about "faux 3D"), but the difference is that in my game, the player as well as every other creature is represented by 3D objects, and they can all jump, pick up other objects, and throw them around. What this means is that sorting by one value, such as a Z position (how far north south a character is on the screen) won't work, because as soon as a smaller creature jumps on top of a larger creature, or a box, and walks backwards, the moment its z value is less than that other creature, it will appear to be behind the object it is actually standing on. I actually originally solved this problem by splitting every object in the game into physics boxes which MUST have a Y height equal to their Z depth. I then based the depth sorting value on the object's y position (how high it is off the ground) PLUS its z position (how far north or south it is on the screen). The problem with this approach is that it requires all moving objects in the game to be split graphically into chunks which match up with a physical box which has its y dimension equal to its z dimension. Which is stupid. So, I got inspired last night to rewrite with a fresh approach. My new method is a little more complex, but I think a little more sane every object which needs to be sorted by depth in the game exposes the interface IDepthDrawable and is added to a list owned by the DepthDrawer object. IDepthDrawable contains public interface IDepthDrawable Rectangle Bounds get possibly change this to a class if struct copying of the xna Rectangle type becomes an issue DepthDrawShape DepthShape get void Draw(SpriteBatch spriteBatch) The Bounds Rectangle of each IDepthDrawable object represents the 2D Axis Aligned Bounding Box it will take up when drawn to the screen. Anything that doesn't intersect the screen will be culled at this stage and the remaining on screen IDepthDrawables will be Bounds tested for intersections with each other. This is where I get a little less sure of what I'm doing. Each group of collisions will be added to a list or other collection, and each list will sort itself based on its DepthShape property, which will have access to the object to be drawn's physics information. For starting out, lets assume everything in the game is an axis aligned 3D Box shape. Boxes are pretty easy to sort. Something like if (depthShape1.Back gt depthShape2.Front) if depthShape1 is in front of depthShape2. depthShape1 goes on top. else if (depthShape1.Bottom gt depthShape2.Top) if depthShape1 is above depthShape2. depthShape1 goes on top. if neither of these are true, depthShape2 must be in front or above. So, by sorting draw order by several different factors from the physics engine, I believe I can get a really correct draw order. My question is, is this a good way of going about this, or is there some tried and true, tested way which is completely different and has somehow completely eluded me on the internets?
12
Making sense of the Game State manager tutorial? I have come across the Game State Managemnet tutorial at http create.msdn.com en US education catalog sample game state management because I thought this would be a good place to start a game off. I have added a new screen, but I am still a bit lost on how everything works. When I make my game, do I only need one more additional screen? just for gameplay? or should I have a different screen for each level?
12
Position sprite at center of screen I am trying to get a sprite to position itself at the center of the screen but nothing seems to be working for me. I'm trying Viewport viewport graphics.GraphicsDevice.Viewport logoPosition new Vector2((viewport.Width towerImage.Width) 2, (viewport.Height towerImage.Height) 2) and spriteBatch.Draw(towerImage, centre, null, Color.White, 0, baseOrigin, 1.0f, SpriteEffects.None, 0) This is my first time using XNA and I don't really have a clue what I'm doing.
12
HLSL Gaussian blur pixelshader blur is not occurring I am trying to use postprocessing to create a gaussian blur, however, no blur is to be seen, what am I doing wrong? I have included the full code at the bottom of this post in a google docs link, but here are the most important bits and pieces. Part of the xna draw method RenderTarget2D renderTarget renderTarget new RenderTarget2D(this.device, screenWidth, screenHeight, true, pp.BackBufferFormat, pp.DepthStencilFormat) this.device.SetRenderTarget(renderTarget) this.device.Clear(ClearOptions.Target ClearOptions.DepthBuffer, Color.DeepSkyBlue, 1.0f, 0) Rectangle screenRectangle new Rectangle(0, 0, screenWidth, screenHeight) Set the effect parameters (the 'simple' technique creates a red lambertian shaded model, like is shown on the image below) effect.CurrentTechnique effect.Techniques "Simple" effect.Parameters "TextureWidth" .SetValue(screenWidth) device.DepthStencilState DepthStencilState.Default device.BlendState BlendState.Opaque Draw the model mesh.Draw() Render our scene this.device.SetRenderTarget(null) effect.CurrentTechnique effect.Techniques "GaussianBlur" spriteBatch.Begin(0, BlendState.Opaque, null, null, null, effect) spriteBatch.Draw((Texture2D)renderTarget, screenRectangle, Color.White) spriteBatch.End() The pixelshader float Pixels 13 6, 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5, 6, float BlurWeights 13 0.002216, 0.008764, 0.026995, 0.064759, 0.120985, 0.176033, 0.199471, 0.176033, 0.120985, 0.064759, 0.026995, 0.008764, 0.002216, float4 GaussianPixelShader(float2 TextureCoordinate TEXCOORD0) COLOR Pixel width float pixelWidth 1 TextureWidth float4 color 0, 0, 0, 1 float2 blur blur.y TextureCoordinate.y for (int i 0 i lt 13 i ) blur.x TextureCoordinate.x Pixels i pixelWidth color tex2D(TextureSampler, blur.xy) BlurWeights i return color What I have further found out by testing The code in the GaussianPixelShader does get executed (if I set it to just return a black color it gives an entire solid black screen) but just doesn't seem to work do the blurring. Images This is how currently my model looks (I cant see any blurring but maybe the blurring is just too light) image. Full Code Link to the shader code and the link to the xna c code.
12
XNA Rendering vertices that only appear within the cameras view I'm making a game in XNA and I recall hearing that professionally made games use a technique to only render the polygons that appear within the cameras projection. I've been trying to find something on this to do something similar in my game, could anyone point me in the right direction? Right now all I have is a plane grid of vertices that you can set the X Y on which is drawn using DrawUserIndexedPrimitives, but I plan to make a bunch of props as scenery items and I can imagine myself running into issues later on if I don't address this now. Thanks
12
XNA Skinning sample, keyframes and time I've been using the skinned sample from XNA tutorials to understand and play FBX files animation. While the animation in all my tests runs correctly, I fail to understand the technic to calculate time versus keyframes. Most of the models I found so far for free and testing purpose on google store all animations into one "take" and split frames into all animations. So, walk would be frame 1 to 14, run 15 to 30, jump 32 to 48, etc. On the other hand, the skinning sample loads all frames and store a calculated time which it will be using to loop the animation. The part where I'm getting confused is on the keyframe part. For example a model I've been trying to load gives me a 12 seconds timespan with 20160 keyframes. While the timespan seems right, the keyframe count seems to have been altered in some way since in Milkshape and in the Autodesk converter the frame count is at 300. What is it doing? Here's my setup for model conversion. I use Milkshape 3D to export a model and its animation to an FBX binary file. Then, I use the Autodesk file converter to convert the file into an ASCII FBX (so far I tried and tested the FBX2012 and version 6.1, which is the same as the "dude.fbx" given with the skinning sample). Processing model inside XNA with the SkinnedModelProcessor given with the skinning sample. What I'm really trying to achieve here is to split animation into smaller clips so I can switch depending on the user action. I'm perfectly fine with counting keyframes, but as you can see, the keyframe count is way too high.
12
Loading levels from .txt or .XML for XNA I'm attemptin to add multiple levels to my pong game. I'd like to simply exchange a few elements with each level, nothing crazy. Just the background texture, the color of the AI paddle (the one on the right side), and the music. It seems that the best way to go about this is by utilizing the StreamReader to read and write the files from XML. If there is a better, or more efficient alternative way then I'm all for it. In looking over the XNA Starter Platformer Kit provided by MS it seems that they've done it in this manner as well. I'm perplexed by a few things, however, namely parts within the Level class which aren't commented. lt summary gt Iterates over every tile in the structure file and loads its appearance and behavior. This method also validates that the file is well formed with a player start point, exit, etc. lt summary gt lt param name "fileStream" gt A stream containing the tile data. lt param gt private void LoadTiles(Stream fileStream) Load the level and ensure all of the lines are the same length. int width List lt string gt lines new List lt string gt () using (StreamReader reader new StreamReader(fileStream)) string line reader.ReadLine() width line.Length while (line ! null) lines.Add(line) if (line.Length ! width) throw new Exception(String.Format("The length of line 0 is different from all preceeding lines.", lines.Count)) line reader.ReadLine() What does width line.Length mean exactly? I mean I know how it reads the line, but what difference does it make if one line is longer than any of the others? Finally, their levels are simply text files that look like this .................... .................... .................... .................... .................... .................... .................... .........GGG........ ......... ........ .................... ....GGG.......GGG... .... ....... ... .................... .1................X. It can't be that easy..... Can it?
12
Camera wont stay behind model after pitch, then rotation I have a camera position behind a model. Currently, if I push the left thumbstick making my model move forward, backward, or strafe, the camera stays with the model. If I push the right thumbstick left or right, the model rotates in those directions fine along with the camera rotating while maintaining its position relatively behind the model. But when I pitch the model up or down, then rotate the model afterwards, the camera moves slightly rotates in a clock like fashion behind the model. If I do a few rotations of the model and try to pitch the camera, the camera will eventually be looking at the side, then eventually the front of the model while also rotating in a clock like fashion. My question is, how do I keep the camera to pitch up and down behind the model no matter how much the model has rotated? Here is what I got Rotates model and pitches camera on its own axis public void modelRotMovement(GamePadState pController) Rotates Camera with model Yaw pController.ThumbSticks.Right.X MathHelper.ToRadians(angularSpeed) AddRotation Quaternion.CreateFromYawPitchRoll(Yaw, 0, 0) ModelLoad.MRotation AddRotation MOrientation Matrix.CreateFromQuaternion(ModelLoad.MRotation) Pitches Camera around model Pitch pController.ThumbSticks.Right.Y MathHelper.ToRadians(angularSpeed) Orbit (yaw) Camera around with model (only seeing back of model) public void cameraYaw(Vector3 axisYaw, float yaw) ModelLoad.CameraPos Vector3.Transform(ModelLoad.CameraPos ModelLoad.camTarget, Matrix.CreateFromAxisAngle(axisYaw, yaw)) ModelLoad.camTarget Raise camera above or below model's shoulders public void cameraPitch(Vector3 axisPitch, float pitch) ModelLoad.CameraPos Vector3.Transform(ModelLoad.CameraPos ModelLoad.camTarget, Matrix.CreateFromAxisAngle(axisPitch, pitch)) ModelLoad.camTarget Call in update method public void updateCamera() cameraYaw(Vector3.Up, Yaw) cameraPitch(Vector3.Right, Pitch) NOTE I tried to use addPitch just like addRotation but it didn't work... UPDATE I understand the problem Im having fully. While Im facing world North or world South, the camera pitches around the model like normal. But lets say I'm facing world East. The camera will still point to the model regardless of the rotation, but when I pitch the camera, it will rise and fall in a clock like fashion around the back of the model. So the camera itself is still pitching as to world's North and South. Not the model's North and South.
12
How can I do a Metroid like transition between two tilemaps with Monogame Extended? I want to do a transition like those in the Metroid games. Here is an example of what i mean https www.youtube.com watch?v RKJ3MAi0ZI0. You enter the door, the screen fades to black and the camera scrolls to the next room where the screen fades in again. I'm using Monogame Extended and i have a TiledMap. I use them like described in the documentation. I have a camera with a view matrix and a projection matrix Camera2D camera ... public void DrawGame(GameTime gameTime, SpriteBatch spriteBatch) var viewMatrix camera.GetViewMatrix() var projectionMatrix Matrix.CreateOrthographicOffCenter(0, gDevice.Viewport.Width, gDevice.Viewport.Height, 0, 0f, 1f) tiledMap.Draw(viewMatrix, projectionMatrix) My idea is now to create a second tiledMap to placing them directly next to the first one where the transition occurs. Then i just have to move the camera from one map to the next one. My problem now is that i have no clue how to put them next to each other. From my understanding i somehow have to use the view and projection matrix to draw the tiledMap but i can't figure out how it should work with two tiledMaps.
12
Alternatives to distance fog I'm looking for some ideas algorithm name for alternative to distance fog. I'm playing around an "infinite" terrain engine. I can't draw the whole map because there are no borders and I don't like the idea of hiding the terrain at a distance with fog.
12
Help Reading this Data in XML as a List (ContentReader) Edit So i'm going to rephrase the question a bit, seeing as now i think know how i'm going to read this data. Looking at this example as my guide http forums.create.msdn.com forums p 53404 323877.aspx This is pretty much what i'm currently doing, and to be clear and show you guys http pastebin.com GxqQcBDg, that's how i'm loading my data. So looking at that guys example from his post, he has a similar layout, his "Enemies" can equal my element "Animated Tiles" and then his "Items" could be equal to my "Tile" objects, at least if you compare my data to his they look extremely similar, and yes i did update the Data as Richard Marskell Drackir suggested, But i'm wondering if i can have "Type" definitions like the guy has in his example, to show what i mean lt Animated Tiles Type "System.Collections.Generic.List Namespace.Class " gt Can that be done? Or is it only the "Asset" element that can have the Type definition? Currently this is what my new data layout looks like http pastebin.com i42166ZQ But currently, it seems to start reading it but i get this error by the first "Tile" Element. So the only difference i see between his amp my layouts are that he has the Asset containing the List definition whereas i have "Animated Tiles". So i'm unsure can any element can have the "Type Blah" definition?
12
Data structure to store map layers in each Tile while keeping the order of terrain, items and monsters intact My game represents its map as a 2D array of tiles, each of which stores a stack of layers. I'm looking for a data structure to efficiently represent this . I want to be able to add layers dynamically, so fixed arrays won't do. Additionally, the layers are applied in zones, to make sure that terrain is always drawn before items and monsters, and that items monsters are drawn before the player. This is the order terrainlayer terraineffectlayers itemlayers monsterlayers playerlayers specialeffectslayers I want to store all those zones in the same data structure, so I can traverse it from end to end in either direction. I also need to be able to add a monster layer that would automatically go at the end of monsterlayers data structure while still having a global object that would let me traverse from the all the layers. I also need the ability to access the data structure with index, so I can get the 3rd monster in the tile easily or remove the 3rd monster. Add will always be sequential, but remove are at random indexes. Does a data structure like this already exist or do I need to make some sort of vector doubly linked list deque hybrid? I have already seen this question but it doesn't help me.
12
Torus World Collision Dection I am looking for a collision detection solution for use when 2d screen wrapping. Specifically, when the image is split between the right and left side I can only detect a collision for a limited area. For example, the program detects the collision when the rectangle intersects the circle in the first image. However, it doesn't in the second image. I am using the Rectangle.Instersects method to check for the collision in both cases. I used the screen wrapping solution at the following link How to create a 2D region where sprites are automatically wrapped? However, since I am not using the physics engine, I am not using the related solution at How to create a very specific kind of joint in Farseer? I am aware of the following question https stackoverflow.com questions 8679304 wrapping drawn image in xna 4 0, and incorporated part of the code to reset the draw rectangle's position when wrapping for both sprites reset draw rectangle for wrapping if (drawRectangle.X lt sprite.Width) drawRectangle.X parentWindowWidth if (drawRectangle.X gt parentWindowWidth) drawRectangle.X parentWindowWidth if (drawRectangle.Y lt sprite.Height) drawRectangle.Y parentWindowHeight if (drawRectangle.Y gt parentWindowHeight) drawRectangle.Y parentWindowHeight This post also says that I have to check for the collision in the two separate positions, but I am having trouble doing so. Any suggestions?
12
XNA Scale only parent I was wondering, is it possible to Scale(Vector3) a ModelBone without scaling its children. Lets say I got a Bone A at position 1,0,3. And one of its children Bone B is at position 1,0,5 (he is touching Bone A). Could I scale Bone A along Z axis without scaling Bone B, but keep Bone B position and rotation so that he is still touching Bone A. Thanks in advance
12
Units issue when exporting from 3DS Max to XNA I am working on a XNA game where we have defined that 1 XNA unit equals to 1 meter. Then, I set meters as system unit in 3DS Max and set to meters the units in the FBX exporter. However, when I export my models, they are much bigger in the game. Am I missing something? What should I do to avoid problems with my units? Investigating the FBX file, I noticed that I it has two values called UnitScaleFactor and OriginalUnitScaleFactor. They both are 100 when I export the files... And if I manually change UnitScaleFactor to 1, it works fine S
12
Keyboard.GetState() only work first time, and Memory increase (not Disposing) EDIT UPDATE 3 I been searching the web for a solution and found several people struggling with Memoryleak using MonoGame while trying to dispose objects. It could be the case that MonoGame should be started and then closed as a own process, not from another program which are my case. When I click on the button, a new thread is created and the MonoGame application is started viThread new Thread(startDemo) viThread.Priority ThreadPriority.Highest viThread.Start() private void startDemo() using (Demo d new Demo()) d.Run() The "Demo" is closed by a Game.Exit command and i have also tried with Disposed(true) without any success. Next time I launch the MonoGame is Keyboard.GetsState() always empty and the memory is incresed. I made a loop where I started and closed the application 100times and it are eating my memory. I have seen lots of discussion about SharpDX not working correcly with dispsing resources. So here I am, stuck. Just want to point out that this worked fine for XNA but not now when changed to MonoGame. And again, thanks for all comments I got so far. I have uploaded a project where you can see the issue by yourself. The second time dosn't the keyboard input work but mouseinput does and the memory is increasing for each time Donwload sln project EDIT UPDATE 4 It is SharpDX which increase the memory, I perform following line before i exit SharpDX.Diagnostics.ObjectTracker.ReportActiveObjects().Length And its increasing all the time. So I guess it isnt released. Someone know how to do that?
12
Avoiding lag when playing sound for first time using Cue.Play In my code I'm using SoundBank.GetCue("cuename") and Cue.Play() to play my sounds. On the xbox whenever I first play a cue I get lag of about about one second. How can I avoid this? I'm thinking I probably have to do something like call GetCue (without playing it) for every Cue I'm going to use, however I don't have a central place where I list all cues I'll want to play, so is there an easy way to do that? Update It seems calling GetCue for all sounds i want to play doesn't work. I'm still getting stuttering in various places in my game when i call GetCue....Play.
12
XNA Distortion Shader problem So I came up with a distortion pixel shader in hlsl, but it has some issues. First of all, here is how it works The shader uses another texture generated by the program as a distortion "map" (if that's the correct term) I called this map a "mask". The shader uses the red values in the mask for horizontal distortion and the blue values as vertical distortion. The green values are not used. It subtracts 0.5 from the red and green values so that they have a range from 0.5 to 0.5 instead of 0 to 1. This lets the distortion go in any direction using only two color values. I let the shader "push" pixels up to 128 pixels. sampler s0 texture textu sampler tex sampler sampler state Texture textu float2 screenSize float4 PixelShaderFunction(float2 coords TEXCOORD0) COLOR0 float4 tex color tex2D(tex sampler, coords) if (tex color.a) float distX (tex color.r 0.5f) (256.0f screenSize.x) tex color.a float distY (tex color.b 0.5f) (256.0f screenSize.y) tex color.a return tex2D(s0, float2(coords.x distX, coords.y distY)) return tex2D(s0, coords) technique Technique1 pass Pass1 PixelShader compile ps 2 0 PixelShaderFunction() "textu" being the mask, "tex color" is the color value from the mask. It also multiplies the distortion by the alpha value in the mask. This seemed to work perfectly at first, but I started noticing some issues. I was using a completely white texture (as the mask) that was blurred around the edges. I set the color of this texture based on its rotation. Here is the method I used for that private Color GetDirectionColor(float rad) Vector2 v new Vector2( (float)Math.Cos(rad Math.PI), (float)Math.Sin(rad Math.PI) ) float r (v.X 0.5f) 0.5f float b (v.Y 0.5f) 0.5f return new Color(new Vector3(r, 0, b)) This allows the texture to "push" pixels in whatever direction it is facing. This method seems to work fine. The problem is, when the texture is rotated more than 135 degrees and less than 315 degrees (as in, the texture is pointing into the upper left half of a circle if you cut it in half at a 45 degree angle) it does something strange. Where the texture is blurred (the alpha values become less than 1) it starts to "push" the pixels in the opposite direction that it should be. I suspect this has to do with my shader and not something else in the program. Possibly the 0.5f part??? I'm terribly sorry if this is confusing... I could not find a better way to word it. Thanks a lot for your help!
12
XNA 3D coordinates seem off I'm going through a book, and the example it gave me seems like is should work, but when I try and implement it, it falls short. My Camera class takes three vectors in to generate View and Projection matrices. I'm giving it a position vector of (0,0,5), a target vector of Vector.Zero and a top vector (which way is up) of Vector.Up. My Three vertices are placed at (0,1,0), ( 1, 1,0), (1, 1,0). It seems like it should work because the vertices are centered around the origin, and thats where I'm telling the camera to look but when I run the game, the only way to get the camera to see the vertices is to set its position to (0,0, 5) and even then the triangle is skewed. Not sure what's wrong here. Any suggestions would be helpful. Just to make sure I've given you guys everything (I don't think these are important as the problem seems to be related to the coordinates, not the ability of the game to draw them) I'm using a VertexBuffer and a BasicEffect. My render code is as follows effect.World Matrix.Identity effect.View camera.view effect.Projection camera.projection effect.VertexColorEnabled true foreach (EffectPass pass in effect.CurrentTechnique.Passes) pass.Apply() GraphicsDevice.DrawUserPrimitives lt VertexPositionColor gt (PrimitiveType.TriangleStrip, verts, 0, 1)
12
What is wrong with my vertex declaration? What is wrong with my vertex declaration below? I am using it with instancing. After adding TextureInformation to it, it renders weird and has an epileptical seizure. public struct VertexInstance IVertexType public Matrix World public Color Color public Vector3 TextureInformation I use arithmetic here to show clearly where these numbers come from You can just type 28 if you want public static readonly int SizeInBytes sizeof(float) 23 Vertex Element array for our struct above public static readonly VertexElement VertexElements new VertexElement(0, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 0), new VertexElement(sizeof(float) 4, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 1), new VertexElement(sizeof(float) 8, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 2), new VertexElement(sizeof(float) 12, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 3), new VertexElement(sizeof(float) 16, VertexElementFormat.Color, VertexElementUsage.TextureCoordinate, 4), new VertexElement(sizeof(float) 20, VertexElementFormat.Vector3, VertexElementUsage.TextureCoordinate, 5) public static VertexDeclaration Declaration get return new VertexDeclaration(VertexElements) VertexDeclaration IVertexType.VertexDeclaration get return new VertexDeclaration(VertexElements)
12
XNA Static classes from game libraries executing after content pipeline extensions, how to avoid the problem? Alright, formulated this way I'm sure it sounds obscure, but I'll do my best to describe my problem. First, let me explain what's wrong with my real source code. I'm making a platformer, and here are the current components of my game a Level, which is holding its own grid of tiles and also the tile sheets and a Tile, which just keeps the name of its tile sheet and index within the tile sheet. All these are within a separate XNA game project, named GameLib. Here is how my levels are formatted in a text file x x . . . . . . . . b g r . . . . . . . . X X X X X X X Where . represents an empty tile, b represents a blue platform, X represents a block with a random color, etc. Instead of doing all the work of loading a level within the Level class, I decided to take advantage of the content pipeline extension and create a LevelContentPipelineExtension. As soon as I started, I quickly realized that I didn't want to hard code 20 lines of the kind if (symbol 'b') return new Tile( ... ) So, in the hope of at least centralizing all the content creation into one class, I made a static class, called LevelContentCreation, which holds the information about which symbol creates what and all this kind of stuff. It also holds a list of all the asset paths of the tile sheets, to load them later on. This class is within my GameLib game library project. The problem is, I'm using this LevelContentCreation static class in both my Level class (to load the actual tile sheets) and my content pipeline extension (to know which symbol represents what tile)... And here's how my LevelContentCreation class looks like public static class LevelContentCreation private static Dictionary lt char, TileCreationInfo gt AvailableTiles CreateAvailableTiles() private static List lt string gt AvailableTileSheets get set ... rest of the class Now, since the LevelContentCreation class is part of the game library, the content pipeline extension tries to use it but the call to CreateAvailableTiles() never happens and I'm unable to load a Level object from the content pipeline. I know this is because the content pipeline executes before the actual compilation or something like that, but how can I fix the problem? I can't really move the LevelContentCreation class to the pipeline extension, because then the Level class wouldn't be able to use it... I'm pretty lost and I don't know what to do... I know these are pretty bad design decisions, and I'd like it if somebody could point me in the right direction. Thank you for your precious time. If anything is not clear enough or if I should provide more information code, please leave a comment below. A little more information about my projects Game XNA Windows game project. Contains references to Engine, GameLib and GameContent GameLib XNA game library project. Contains references to Engine GameContent XNA content project. Contains references to LevelContentPipelineExtension Engine XNA game library project. No references. LevelContentPipelineExtension XNA content pipeline extension. Contains references to Engine and GameLib I know close to nothing about XNA 4.0 and I'm a little bit lost about how content works now. If you need more information, tell me.
12
Efficient way to avoid shadow "streaks" beyond bounds of shadow map BACKGROUND INFO Using MonoGame. To maximize shadow resolution, I've got a shadow map that covers only the area closest to the camera. (I am aware of Cascading shadow maps, but for now, I am willing to simply lose shadows far away, in exchange for higher resolution near the camera.) Specifically, I am rendering shadows of tree billboards, that are then cast on to a ground terrain. First version worked great except for one issue. If a shadow is drawn that touches an edge of the shadow map, then that final row (or column) of pixels is REPEATED by the "Clamp" setting of the sampler. Result is a shadow "streak" that continues from the edge of map into the distance on the ground. To eliminate those streaks, give full illumination when "outside" of shadow map, I added test to my lookup function to return full illumination (1.0) if UV outside of valid range if (texCoord.x lt 0 texCoord.x gt 1 texCoord.y lt 0 texCoord.y gt 1) return 1.0f ... followed by the code that looks up in shadow map, returns an illumination in range 0..1. This works. I have two questions about this Is there a more efficient way to test these 4 conditions, or to avoid the need to test? Is there an efficient way to solve this when the shadow map is created? The sampler is set to "clamp", so if the first and last row and column of map were all "untouched" (held the default depth value or illumination value, depending on the shadowing technique), then I would not need to do any special tests when using the map "clamp" would retrieve an edge pixel, so if those all were "untouched" by shadows, I would get the desired result. 2.b. It just occurred to me that one solution to (2) is to write the default value back into the four edge rows columns. after all shadows are rendered What is an efficient way to do that?
12
How can I determine if a cube is adjacent to another cube, and optimize its buffers if so? I'm trying to optimize the rendering of a collection of cubes, (based on an answer I was given to another question I asked). I understand the logic behind occlusion culling, but I'm having trouble with the code. When I create a cube, I want to determine if that cube is touching another existing cube, and if so I don't want to generate the redundant data in my vertex or index buffers. I'm planning on making a method that I call from my cube constructor so that everytime I create a cube, these checks are made, and neither occluded face is ever drawn. How would I go about this?
12
How can I make an object's hitbox rotate with its texture? In XNA, when you have a rectangular sprite that doesnt rotate, it's easy to get its four corners to make a hitbox. However, when you do a rotation, the points get moved and I assume there is some kind of math that I can use to aquire them. I am using the four points to draw a rectangle that visually represents the hitboxes.
12
MonoGame Draw thousands of quads without hardware instancing In my game, every bit of geometry is a textured quad billboard in 3D. I have many thousands of these things on screen at once, sometimes with overdraw. As I understand it, there are a few ways I can go about drawing these Have a single VBO per type of quad (ie, unique set of texture coords). Batch the VBO and texture, but make multiple draw calls. Looks something like this foreach (Quad quad in quadTypes) The VBO just contains 4 6 vertices. GraphicsDevice.SetVertexBuffer(quad. vertexBuffer) Shader.SetTexture(quad. texture) Draw each instance using multiple draw calls foreach(QuadInstance instance in quad. instances) Shader.SetWorldMatrix(instance. worldMatrix) foreach(ShaderPass pass in Shader. passes) pass.Apply() GraphicsDevice.DrawPrimitive(TRIANGLES) Make a single draw call by somehow combining all the triangles of all the instances of a quad type. Looks something like this foreach (Quad quad in quadTypes) Shader.SetTexture(quad. texture) Probably can cache a vertex buffer for when quads are created destroyed instead. VertexBuffer vertexBuffer new VertexBuffer() foreach(QuadInstance instance in quad. instances) Add all of the (world transformed) triangles of this instance to the vertex buffer vertexBuffer.AddAll(instance.CreateTriangles()) Draw all the quads with a single draw call and vertex buffer. GraphicsDevice.SetVertexBuffer(vertexBuffer) foreach(ShaderPass pass in Shader. passes) pass.Apply() GraphicsDevice.DrawPrimitive(TRIANGLES) True hardware instancing. This is currently how I do it in my (XNA HiDef profile) game, but I can't figure out a way to get it to work in Monogame. With true hardware instancing, each instance is represented as a vertex, and the GPU creates all the necessary duplicate vertices in a single draw call. In general, which one of these is most desirable? 1) makes many draw calls, but saves the most memory. 2) has a single draw call, but requires creating a vertex buffer for all of the instances, which seems really inefficient, and 3) has the best of both worlds but is not widely supported. Is there a fourth way that I'm missing?
12
Why use this equation to get a percentage? In an XNA book I read that this code does an action with a 0.2 of probability but I don't' understand why float chance 0.2f if((float)rand.Next(0,1000) 10 lt chance) ... I understand the statement, but not the reasoning for that equation. Can anyone explain me, please?
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 to Create a New Instance of a Game Object Alright, please don't scald me here haha. I'm very new to XNA, C , and game development as a whole. I have done web design, but that is my main experience with programming. It is a Space Invaders type ish game. In the code below I have a Meteor class. In this class I want to create a meteor in a random location (on the X axis) and then have it fall. I don't care much about it doing damage yet. I can always get one meteor created, and falling, yet when I press 'M' to create another instance of the class it isn't creating another meteor. I could very possibly be going about this entirely wrong...please forgive me if I am. class Meteor private Random randomNumber new Random() private Rectangle position private int fallSpeed private double damage private int x, y 0 private int WIDTH, HEIGHT List to hold meteors created (holds instance of Meteor class) List lt Meteor gt meteors new List lt Meteor gt () Texture for the meteor private Texture2D meteor lt summary gt Create the meteor and each meteor's properties lt summary gt public Meteor() HEIGHT randomNumber.Next(0, 60) WIDTH HEIGHT fallSpeed randomNumber.Next(0, 10) damage fallSpeed 2 x randomNumber.Next(0, 600) Randomly generates where meteor will spawn on X axis public void createMeteor() meteors.Add(new Meteor()) lt summary gt Load content (graphics) relating to the meteor lt summary gt public void LoadContent(ContentManager Content) Load meteor texture meteor Content.Load lt Texture2D gt ("Sprites meteor") lt summary gt Update the meteors position lt summary gt public void Update() Update position of metoer (falling) y Testing purposes mostly...I want meteors to be created when I press 'M' if (Keyboard.GetState().IsKeyDown(Keys.M)) createMeteor() lt summary gt Draw the metoer (and it's new position). lt summary gt public void Draw(SpriteBatch spriteBatch) position new Rectangle(x, y, HEIGHT, WIDTH) spriteBatch.Draw(meteor, position, Color.White) So I can get the damage public double getDamage() return damage
12
Better quality texture when zooming Is there any way to have better quality textures ? I thought that creating huge textures will improve their quality in game, that's why I draw textures with 0.25f or 0.5f scale. I understand that computer can't display 4 pixels in 1 screen pixel, but how people do to have beautiful sprites while zooming ? even on smartphones... Hope you can help me.
12
Change opacity for texture or sprites in XNA Is there a way to change the opacity or transparency for a texture or sprite?
12
What kind of performance issues does multiple instances of the exact same object have on a game? I'm fairly new to programming, and I've pretty much learned all the things I know on the go, while working on projects. The problem is that there some things that I just don't know where to begin searching. My question is about performance, and how can multiple instances of the same object affect it Specifically, I'm talking about XNA's "GraphicsDevice" class. I have it instanced on four different parts of my game, and in three of those, the object has the exact same values for all the attributes. So, in that case, should I be using the same instance of GraphicsDevice, passing it as a parameter, even if I use it in different classes? I apologize if the question seems redundant, but like I said, I've taught myself most of what I know, so there are quite a few "holes" in my learning process.
12
How can I create a resizeable 2D camera with parallax scrolling? I want to create a Windows Phone jump and run game with parallax scrolling. The character should always be in centered in the viewport. I use the following camera so that the viewport looks on every resolution the same Vector2 vp, gameWorldSize new Vector2(800, 480) vp new Vector2(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height) ScaleX vp.X gameWorldSize.X ScaleY vp.Y gameWorldSize.Y Scale Math.Min(ScaleX, ScaleY) Vector2 PlayerPosition Vector2 Viewport float Scale public Matrix GetMatrix(float scrollingspeed) return Matrix.CreateTranslation(new Vector3( PlayerPosition.X, PlayerPosition.Y, 0) scrollingspeed) Matrix.CreateScale(Scale, Scale, 1) Matrix.CreateTranslation(Viewport.X 2, Viewport.Y 2, 0) I draw the sprites like this spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, null, camera.GetMatrix(0.8f)) BackgroundLayer1.Render(spriteBatch) spriteBatch.End() spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, null, camera.GetMatrix(1.0f)) Player.Render(spriteBatch) spriteBatch.End() in the Player class batch.Draw(Playertex, new Rectangle(400, 240, Playertex.Width, Playertex.Height), null, Color.White, 0, new Vector2(Playertex.Width 2, Playertex.Height 2), SpriteEffects.None, 0f) in the BackgroundLayer1 class batch.Draw(Background1tex, new Rectangle(400, 240, Background1tex.Width, Background1tex.Height), null, Color.White, 0, new Vector2(Background1tex.Width 2, Background1tex.Height 2), SpriteEffects.None, 1.0f) The camera is working fine and the player is always in the center of the viewport, but I don't know how to implement Parallax Scrolling. What is the best way to implement Parallax Scrolling? How can I create a resizeable 2D viewport that follows the player and supports parallax scrolling? UPDATE1 In addition, the background sprites shouldn't repeat in a loop, because I have ten 800x480 pixel sprites that are drawn one after another. For example, the first sprite is drawn at (0,0), the second at (800,0), the third at (1600,0), The last sprite(number 10) is the end of the level. The player can move back but not further. I will create more than one layer of sprites, but every layer with a different speed factor to create the Parallax Scrolling. How can I add the speed factor so that the background sprites move slower than the player sprite? UPDATE2 If I draw "BackgroundLayer1" with a scrolling speed of 1.0f, the sprite is drawn on the correct position, but if I change the scrolling speed to another value(for example 0.8f), then the sprites of "BackgroundLayer1" aren't drawn on the correct position. Why are the sprites of "BackgroundLayer1" not drawn on the same position if I change the scrolling speed? What is wrong? The sprites should be drawn on the same positions, even if I change the scrolling speed. In these two pictures, you see the differences if I change the scrolling speed of BackgroundLayer1 scrollingspeed 1.0f http s1.directupload.net images 140505 qdi6cqwz.jpg scrollingspeed 0.8f http s1.directupload.net images 140505 56ferzuv.jpg
12
Most efficient way to hide out of bounds object in tile based environment I am working on a desktop game in C , with Monogame framework. I am storing the tile instances in a 2D Array, for the sake of easy collision detection. But the levels are big (often 100x100 or bigger) and there are lots of tiles out of the screen bounds all the time which I should not draw. At the moment I'm running through the arrays and checking whether they are in the screen bounds or outside, but that may not be too efficient due to the big count of the tiles. Is there any better way to hide out of bounds tiles?
12
How would I go about using FXAA in XNA? This isn't so much a "give me teh codez" as it is a request for the "right" steps to go through. I want to implement FXAA in XNA, but I'm a relative newb to the graphics side of game dev, so I'm not sure what the most efficient way to do this would be. My first hunch is to render the scene into a texture, and then render that texture on a rectangle, with the FXAA code in a pixel shader. However, I would actually be surprised if there was no more efficient way to do it.
12
Consistency of DirectX models Is there a way to check the consistency of a DirectX model (.x) ? Whilst compiling .x files with XNA GameStudio 3.1 compilation is aborted with the following error message Error 2 Could not read the X file. The file is corrupt or invalid. Error code D3DXFERR PARSEERROR. C WFP Browser Content m.x KiviBrowser Some models compile correctly without any error warning and some abort as described. The files of each model have several thousand lines. I am creating the files in Googles SketchUp 8 where they all look fine and don't show any sign of corruption. Suppose I have such a model my XNA compiler won't compile because their is an inconsistency somewhere in the file how could I identify this in order to correct it ?
12
Loading and storing content efficiently So for example I have a class called TypingKeyboard. It allows you to display a string while it's being typed by the computer with sounds. I need one in the menu, for the title. And one for the credits, and some in game. So loading every sound and storing it to the RAM for every instance of TypingKeyboard is not very efficient. So, I want to make a class that already holds these sounds, then call it when I need it, so I don't have to load everything. How do I design this? I mean, how do you get these sounds loading and then make them accessible without initializing a class for it?
12
Rendering multiple RenderTargets to the screen Let's say I have a background and a set of entities. I have managed to draw the background into a Texture2D using a RenderTarget I have also managed to draw all my entities into another RenderTarget Now I want to take these two Textures and render them on the screen as so Top level rendering entitiesSystem.Process() background.Process() Texture2D entitiesTexture entitiesSystem.EntitiesTexture Texture2D backgroundTexture background.BackgroundTexture graphicsDevice.SetRenderTarget(null) graphicsDevice.Clear(Color.Black) spriteBatch.Begin() spriteBatch.Draw( backgroundTexture, LevelManager.LEVEL RECTANGLE, null, Color.White, 0.0f, Vector2.Zero, SpriteEffects.None, 1 ) spriteBatch.Draw( entitiesTexture, LevelManager.LEVEL RECTANGLE, null, Color.White, 0.0f, Vector2.Zero, SpriteEffects.None, 0 ) spriteBatch.End() Here is how the background system renders the background graphicsDevice.SetRenderTarget(BackgroundTexture) spriteBatch.Begin() for (int i 0 i lt 2 i ) spriteBatch.Draw(textures i , positions i , Color.White) spriteBatch.End() Almost the same thing happens for the entities I set the render target to the relevant one (not the same as the one for the background), start the spritebatch (again, not the same one), draw the entities and end the spritebatch. If I set BlendMode to additive, the result is correct (they blend together). However, if I set to to AlphaBlend, then I can only render one of them (depending on the SpriteSortMode). I have come as far as understanding that the problem lies in not preserving... something, but I am not sure how to preserve it P By the way, I read that multiple render targets are not supported for the XBOX... Soooooooo... what is the alternative of doing what I am doing now?
12
How can I export a model using the CAT bone system into XNA? Has anyone successfully used the CAT bone system in 3ds Max and exported the file into XNA? If so, what was your method of doing so? There are a number of methods of doing this, apparently, but the ones I've tried have not worked. I used the Panda Exporter which creates an .X file. This seems to be the latest way of going about this, but when it's loaded in XNA, there is an error saying something about the bone weights. This happens when I export with and without CAT bones.
12
Portable sound and music for XNA MonoGame? What is the best (recommended) way to integrate audio (both sound effect and music) in a game project (using C XNA) targeting multiple desktop platforms (W7, W8 Metro, Linux, OSX, ...) via MonoGame. XACT was the usual way in XNA but it is deprecated in W8 and also cannot be used with MonoGame, I am looking for an alternaive. Is there one?
12
How much memory does a texture take up on the GPU? A large png on disk may only take up a couple megabytes but I imagine that on the gpu the same png is stored in an uncompressed format which takes up much more space. Is this true? If it is true, how much space?
12
Mouse Interaction in 3D space (ray) I use this code public static Ray CalculateRay(Vector2 mouseLocation, Matrix view, Matrix projection, Viewport viewport) Vector3 nearPoint viewport.Unproject(new Vector3(mouseLocation.X, mouseLocation.Y, 0.0f), projection, view, Matrix.Identity) Vector3 farPoint viewport.Unproject(new Vector3(mouseLocation.X, mouseLocation.Y, 1.0f), projection, view, Matrix.Identity) Vector3 direction farPoint nearPoint direction.Normalize() return new Ray(nearPoint, direction) to calculate a ray for mouse position x y. But the result is everytime again NaN.. If I try it with .99f it works but the collision detection is not exact.. How can I determine whether the cursor hits and model in 3d space?
12
Getting a 3d mouse position I've looked at a few tutorials about picking and the method Unproject, so I have an idea of how getting the mouse in 3d space is done. The code I have does display a mouse position, but it is way off of the actual position the mouse is at. public Vector3 FindWhereClicked(MouseState ms) Vector3 nearScreen new Vector3(ms.X, ms.Y, 0) Vector3 farScreen new Vector3(ms.X, ms.Y, 1) Vector3 nearWorld device.Viewport.Unproject(nearScreen, cam.proj, cam.view, Matrix.Identity) Vector3 farWorld device.Viewport.Unproject(farScreen, cam.proj, cam.view, Matrix.Identity) Vector3 direction farWorld nearWorld float zFactor nearWorld.Y direction.Y Vector3 zeroWorldPoint nearWorld direction zFactor return zeroWorldPoint This code is from another thread I found on here. I'm guessing the problem is the near and far world variables. public ThirdPersonCam() proj Matrix.CreatePerspectiveFieldOfView(0.78f, 1.7777f, 1f, 10000f) public void CameraUpdate(Matrix objectToFollow) Vector3 camPosition objectToFollow.Translation (objectToFollow.Backward 10) (objectToFollow.Up 2) Vector3 camTarget objectToFollow.Translation view Matrix.CreateLookAt(camPosition, camTarget, Vector3.Up) The variables are grabbed from my camera class, but I don't know why it isn't working. A point that's supposed to be at 0, 0, 0 ends up being at something like 36, 1, 57
12
How (update,set, apply) dynamically color on a model of a XNA project? I encounter a problem for set a background color on my model instantiated. I can change the texture but not change color. Is there a parameter for change the color ? Or change the opacity ? I am looking for a way to highlight a model. thank you so much Here is my code used Everything works except the two last line. I searched but can not find name parameter for color and opacity Does not work effect.Parameters "Color" .SetValue(new Vector3(0,1,0)) effect.Parameters "Opacity" .SetValue(0.5f) void DrawModelHardwareInstancing(Model model, Matrix modelBones, Matrix instances, Matrix view, Matrix projection) ....... foreach (ModelMesh mesh in model.Meshes) foreach (ModelMeshPart meshPart in mesh.MeshParts) Tell the GPU to read from both the model vertex buffer plus our instanceVertexBuffer. Game.GraphicsDevice.SetVertexBuffers( new VertexBufferBinding(meshPart.VertexBuffer, meshPart.VertexOffset, 0), new VertexBufferBinding(instanceVertexBuffer, 0, 1) ) Game.GraphicsDevice.Indices meshPart.IndexBuffer Set up the instance rendering effect. Effect effect meshPart.Effect effect.CurrentTechnique effect.Techniques "HardwareInstancing" effect.Parameters "World" .SetValue(modelBones mesh.ParentBone.Index ) Work perfect effect.Parameters "View" .SetValue(view) effect.Parameters "Projection" .SetValue(projection) effect.Parameters "Texture" .SetValue(textureInstancedModel) Does not work effect.Parameters "Color" .SetValue(new Vector3(0,1,0)) effect.Parameters "Opacity" .SetValue(0.5f) Draw all the instance copies in a single call. foreach (EffectPass pass in effect.CurrentTechnique.Passes) pass.Apply() Game.GraphicsDevice.DrawInstancedPrimitives(PrimitiveType.TriangleList, 0, 0, meshPart.NumVertices, meshPart.StartIndex, meshPart.PrimitiveCount, instances.Length) ........
12
x axis detection issues platformer starter kit I've come across a problem with the collision detection code in the platformer starter kit for xna.It will send up the impassible flag on the x axis despite being nowhere near a wall in either direction on the x axis, could someone could tell me why this happens ? Here is the collision method. lt summary gt Detects and resolves all collisions between the player and his neighboring tiles. When a collision is detected, the player is pushed away along one axis to prevent overlapping. There is some special logic for the Y axis to handle platforms which behave differently depending on direction of movement. lt summary gt private void HandleCollisions() Get the player's bounding rectangle and find neighboring tiles. Rectangle bounds BoundingRectangle int leftTile (int)Math.Floor((float)bounds.Left Tile.Width) int rightTile (int)Math.Ceiling(((float)bounds.Right Tile.Width)) 1 int topTile (int)Math.Floor((float)bounds.Top Tile.Height) int bottomTile (int)Math.Ceiling(((float)bounds.Bottom Tile.Height)) 1 Reset flag to search for ground collision. isOnGround false For each potentially colliding tile, for (int y topTile y lt bottomTile y) for (int x leftTile x lt rightTile x) If this tile is collidable, TileCollision collision Level.GetCollision(x, y) if (collision ! TileCollision.Passable) Determine collision depth (with direction) and magnitude. Rectangle tileBounds Level.GetBounds(x, y) Vector2 depth RectangleExtensions.GetIntersectionDepth(bounds, tileBounds) if (depth ! Vector2.Zero) float absDepthX Math.Abs(depth.X) float absDepthY Math.Abs(depth.Y) Resolve the collision along the shallow axis. if (absDepthY lt absDepthX collision TileCollision.Platform) If we crossed the top of a tile, we are on the ground. if (previousBottom lt tileBounds.Top) isOnGround true Ignore platforms, unless we are on the ground. if (collision TileCollision.Impassable IsOnGround) Resolve the collision along the Y axis. Position new Vector2(Position.X, Position.Y depth.Y) Perform further collisions with the new bounds. bounds BoundingRectangle This is the section which deals with collision on the x axis else if (collision TileCollision.Impassable) Ignore platforms. Resolve the collision along the X axis. Position new Vector2(Position.X depth.X, Position.Y) Perform further collisions with the new bounds. bounds BoundingRectangle Save the new bounds bottom. previousBottom bounds.Bottom
12
HLSL Pixel Shader Color depending on condition I am new to shaders and HLSL so bare with me on this one. I have a 2D tile map in my game and want to create a mini map, at first I was just copying all the data from one sprite batch to another and rendering it in a smaller camera. This obviously has a performance issue. So I want to make a mini map that is composed of coloured pixels depending on what is in that particular cell. I have a basic shader going at the moment that converts tex coordinates to pixel position but now I need a way to determine what color to set it. My instant decision was to simply pass in a 2d array of colors and grab the color using the x and y coordinate of the pixel, this crashed lol. Here is what I have so far for the shader sampler s0 The width and height of the texture being sampled int width, height float4 PixelShaderFunction(float2 coords TEXCOORD0) COLOR0 float4 color tex2D(s0, coords) Covert the tex coordinates to pixel coordinates int2 tc int2(width coords.x, height coords.y) Here I need to do some sort of check or something? return color technique Technique1 pass Pass1 PixelShader compile ps 2 0 PixelShaderFunction() How can I pass the color data to the pixel shader so it knows what color to set each pixel? I already know how to pass data but not sure how I can represent that data to pass it. My map is every changing and units are moving around constantly, so the data will be passed in almost every frame.
12
XNA HLSL what happens if I grab a pixel outside a texture? I'm using the tex2D function of HLSL, and I am wondering what will happen if I try to grab a pixel from a pixel coordinate outside of my texture (as an example 1.1). Will it clamp? Will it repeat the texture and grab something else? Will it return transparent?
12
Is it possible to use Windows Forms in an XNA project? Is it possible to keep a Windows Form inside a XNA project? I tried it but without success. Below I'm showing how my main file is. using System namespace JogoSuecaOnline if WINDOWS XBOX static class Program lt summary gt The main entry point for the application. lt summary gt static void Main(string args) MainMenu menu new MainMenu() menu.Show() endif
12
How to pause and resume a game in XNA using the same key? I'm attempting to implement a really simple game state system, this is my first game trying to make a Tetris clone. I'd consider myself a novice programmer at best. I've been testing it out by drawing different textures to the screen depending on the current state. The 'Not Playing' state seems to work fine, I press Space and it changes to 'Playing', but when I press 'P' to pause or resume the game nothing happens. I tried checking current and previous keyboard states thinking it was happening to fast for me to see, but again nothing seemed to happen. If I change either the pause or resume, so they're both different, it works as intended. I'm clearly missing something obvious, or completely lacking some know how in regards to how update and or the keyboard states work. Here's what I have in my Update method at the moment protected override void Update(GameTime gameTime) KeyboardState CurrentKeyboardState Keyboard.GetState() Allows the game to exit if (CurrentKeyboardState.IsKeyDown(Keys.Escape)) this.Exit() TODO Add your update logic here if (CurrentGameState GameStates.NotPlaying) if (CurrentKeyboardState.IsKeyDown(Keys.Space)) CurrentGameState GameStates.Playing if (CurrentGameState GameStates.Playing) if (CurrentKeyboardState.IsKeyDown(Keys.P)) CurrentGameState GameStates.Paused if (CurrentGameState GameStates.Paused) if (CurrentKeyboardState.IsKeyDown(Keys.P)) CurrentGameState GameStates.Playing base.Update(gameTime)
12
XNA C Adding objects to List in another class Hi all i started creating this XNA C version of Space invaders to get better at xna since i've only been using it for about 4 days. I've managed fine till now.. So my problem is adding my Bullets to a List in another class. So i've tried working out the solution for about 3 hours now and i hope you guys can help me. In the Player.cs class i've got a method FireBullet() wich should create a new Bullet.cs class and add it to the list in Game1.cs (it does not do this when you debug) in theory this should work(i think). Linking all the corresponding classes will take too much room so i've uploaded it to github https github.com Breinss Space Invaders XNA C says C in title ran out of character ment to be C Thanks in advanced!
12
generating complex maps in xna I just wonder how does these maps like in this video are made. http www.youtube.com watch?v TM6kcOau5oQ I was looking for some tutorials on the web but no success. All I found was some 2D Vectors (Matrixes) with 0,1,2 values on it but I think these maps are generated and stored in a different ways. Can somebody help me or give me some advice about these maps. I saw some presentations about indie games and I was just amazed by these games. I want to make my own game. I am a beginner and already started an XNA book and some tutorials. I would like to learn how these games are made. Thanks!
12
Character jumping movement in isometric tile When I want to draw my character moving from one tile to another, I would find the displacement vector between two tile's drawing offset and let the character walk in a linear line toward that direction until it complete this displacement vector. Now, I want to make my character jump from higher lower tile to lower higher tile. I have a drawing location (x,y) for the texture, start and end. However, I want it to motion like a projectile, not a linear line. Therefore, given 2 point, start and end point, how would I motion my character in a jumping motion form (maybe it's a parabolic form)?
12
Biased, conservative random walk I have a sprite which has Velocity and Position, either stored as Vector2. At each Update cycle, velocity is added to the position. I would like to give the sprite a third vector, Target. New targets may be given at any iteration. I would like the sprite to essentially move in a random walk pattern, however two parameters must be exposed A typical random walk is equally likely to increase or decrease the distance to any given Target (plus the small chance of tangential movement). I must be able to bias my random walk such that, while still random, the direction on which the sprite "decides" should be more likely to bring it closer to Target. The random walk should be "smooth" the sprite should not rapidly change direction, as this will look like it's "flickering" or "trembling" to the player. It should gradually veer this way or that, moving randomly, while slowly getting closer when averaged. What is a good, simple way to do this? If possible, give the answer as a Vector2 RandomWalk(Vector2 target) method. I already have a NextGaussian(mean, stdev) method available, if that is helpful.
12
SpriteBatch memory leak I have a strange problem with XNA 4. I'm constructing a SpriteBatch using this.spriteBatch new SpriteBatch( GraphicsDevice ) . This leads to a memory leak up to 600 MB memory consumption. This problem didn't exist two days ago. I have a static class called Resources public static GraphicsDeviceManager gdm This gets set in the Game constructor public class Game Microsoft.Xna.Framework.Game public Game() Resources.gdm new GraphicsDeviceManager( this ) Content.RootDirectory "Content" In the Initialize Method I'm creating a SpriteBatch in the Resources protected override void Initialize() base.Initialize() Resources.Game this Resources.spriteBatch new SpriteBatch( GraphicsDevice ) At the point Resources.spriteBatch new SpriteBatch( GraphicsDevice ) it allocates up to 600 MB memory. Why is XNA allocating so much after I created a SpriteBatch? How can I fix it? (It worked two days ago and I didn't change anything that could cause this problem.)