Search Results

Search found 1663 results on 67 pages for 'xna'.

Page 10/67 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • Loading levels from .txt or .XML for XNA

    - by Dave Voyles
    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. /// <summary> /// 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. /// </summary> /// <param name="fileStream"> /// A stream containing the tile data. /// </param> private void LoadTiles(Stream fileStream) { // Load the level and ensure all of the lines are the same length. int width; List<string> lines = new List<string>(); 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?

    Read the article

  • Get Specific depth values in Kinect (XNA)

    - by N0xus
    I'm currently trying to make a hand / finger tracking with a kinect in XNA. For this, I need to be able to specify the depth range I want my program to render. I've looked about, and I cannot see how this is done. As far as I can tell, kinect's depth values only work with pre-set ranged found in the depthStream. What I would like to do is make it modular so that I can change the depth range my kinect renders. I know this has been down before but I can't find anything online that can show me how to do this. Could someone please help me out? I have made it possible to render the standard depth view with the kinect, and the method that I have made for converting the depth frame is as follows (I've a feeling its something in here I need to set) private byte[] ConvertDepthFrame(short[] depthFrame, DepthImageStream depthStream, int depthFrame32Length) { int tooNearDepth = depthStream.TooNearDepth; int tooFarDepth = depthStream.TooFarDepth; int unknownDepth = depthStream.UnknownDepth; byte[] depthFrame32 = new byte[depthFrame32Length]; for (int i16 = 0, i32 = 0; i16 < depthFrame.Length && i32 < depthFrame32.Length; i16++, i32 += 4) { int player = depthFrame[i16] & DepthImageFrame.PlayerIndexBitmask; int realDepth = depthFrame[i16] >> DepthImageFrame.PlayerIndexBitmaskWidth; // transform 13-bit depth information into an 8-bit intensity appropriate // for display (we disregard information in most significant bit) byte intensity = (byte)(~(realDepth >> 8)); if (player == 0 && realDepth == 00) { // white depthFrame32[i32 + RedIndex] = 255; depthFrame32[i32 + GreenIndex] = 255; depthFrame32[i32 + BlueIndex] = 255; } // omitted other if statements. Simple changed the color of the pixels if they went out of the pre=set depth values else { // tint the intensity by dividing by per-player values depthFrame32[i32 + RedIndex] = (byte)(intensity >> IntensityShiftByPlayerR[player]); depthFrame32[i32 + GreenIndex] = (byte)(intensity >> IntensityShiftByPlayerG[player]); depthFrame32[i32 + BlueIndex] = (byte)(intensity >> IntensityShiftByPlayerB[player]); } } return depthFrame32; } I have a strong hunch it's something I need to change in the int player and int realDepth values, but i can't be sure.

    Read the article

  • Particle System in XNA - cannot draw particle

    - by Dave Voyles
    I'm trying to implement a simple particle system in my XNA project. I'm going by RB Whitaker's tutorial, and it seems simple enough. I'm trying to draw particles within my menu screen. Below I've included the code which I think is applicable. I'm coming up with one error in my build, and it is stating that I need to create a new instance of the EmitterLocation from the particleEngine. When I hover over particleEngine.EmitterLocation = new Vector2(Mouse.GetState().X, Mouse.GetState().Y); it states that particleEngine is returning a null value. What could be causing this? /// <summary> /// Base class for screens that contain a menu of options. The user can /// move up and down to select an entry, or cancel to back out of the screen. /// </summary> abstract class MenuScreen : GameScreen ParticleEngine particleEngine; public void LoadContent(ContentManager content) { if (content == null) { content = new ContentManager(ScreenManager.Game.Services, "Content"); } base.LoadContent(); List<Texture2D> textures = new List<Texture2D>(); textures.Add(content.Load<Texture2D>(@"gfx/circle")); textures.Add(content.Load<Texture2D>(@"gfx/star")); textures.Add(content.Load<Texture2D>(@"gfx/diamond")); particleEngine = new ParticleEngine(textures, new Vector2(400, 240)); } public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) { base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen); // Update each nested MenuEntry object. for (int i = 0; i < menuEntries.Count; i++) { bool isSelected = IsActive && (i == selectedEntry); menuEntries[i].Update(this, isSelected, gameTime); } particleEngine.EmitterLocation = new Vector2(Mouse.GetState().X, Mouse.GetState().Y); particleEngine.Update(); } public override void Draw(GameTime gameTime) { // make sure our entries are in the right place before we draw them UpdateMenuEntryLocations(); GraphicsDevice graphics = ScreenManager.GraphicsDevice; SpriteBatch spriteBatch = ScreenManager.SpriteBatch; SpriteFont font = ScreenManager.Font; spriteBatch.Begin(); // Draw stuff logic spriteBatch.End(); particleEngine.Draw(spriteBatch); }

    Read the article

  • How to do proper Alpha in XNA?

    - by Soshimo
    Okay, I've read several articles, tutorials, and questions regarding this. Most point to the same technique which doesn't solve my problem. I need the ability to create semi-transparent sprites (texture2D's really) and have them overlay another sprite. I can achieve that somewhat with the code samples I've found but I'm not satisfied with the results and I know there is a way to do this. In mobile programming (BREW) we did it old school and actually checked each pixel for transparency before rendering. In this case it seems to render the sprite below it blended with the alpha above it. This may be an artifact of how I'm rendering the texture but, as I said before, all examples point to this one technique. Before I go any further I'll go ahead and paste my example code. public void Draw(SpriteBatch batch, Camera camera, float alpha) { int tileMapWidth = Width; int tileMapHeight = Height; batch.Begin(SpriteSortMode.Texture, BlendState.AlphaBlend, SamplerState.PointWrap, DepthStencilState.Default, RasterizerState.CullNone, null, camera.TransformMatrix); for (int x = 0; x < tileMapWidth; x++) { for (int y = 0; y < tileMapHeight; y++) { int tileIndex = _map[y, x]; if (tileIndex != -1) { Texture2D texture = _tileTextures[tileIndex]; batch.Draw( texture, new Rectangle( (x * Engine.TileWidth), (y * Engine.TileHeight), Engine.TileWidth, Engine.TileHeight), new Color(new Vector4(1f, 1f, 1f, alpha ))); } } } batch.End(); } As you can see, in this code I'm using the overloaded SpriteBatch.Begin method which takes, among other things, a blend state. I'm almost positive that's my problem. I don't want to BLEND the sprites, I want them to be transparent when alpha is 0. In this example I can set alpha to 0 but it still renders both tiles, with the lower z ordered sprite showing through, discolored because of the blending. This is not a desired effect, I want the higher z-ordered sprite to fade out and not effect the color beneath it in such a manner. I might be way off here as I'm fairly new to XNA development so feel free to steer me in the correct direction in the event I'm going down the wrong rabbit hole. TIA

    Read the article

  • Collision detection problem in XNA

    - by Fantasy
    I'm having two problems with my collision detection in XNA. There are two boxes, the red box represents a player and the blue box represents a wall. The first problem is when the player moves to the upper side or bottom side of the wall and collides with it, and then try to go to the left or right, the player will just jump in the opposite direction as seen in the video. However if I go to the right side or the left side of the wall and try to go up or down the player will smoothly go up or down without jumping. The second problem is that when I collide with the box and my key is still pressed down the blue box goes half way through red box and and goes back out and it keeps doing that until I stop pressing the keyboard. its not very clear on the video but the keeps going in and out really fast until I stop pressing the key. Here is a video example:- http://www.youtube.com/watch?v=mKLJsrPviYo and Here is my code Vector2 Position; Rectangle PlayerRectangle, BoxRectangle; float Speed = 0.25f; enum Direction { Up, Right, Down, Left }; Direction direction; protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); KeyboardState keyboardState = Keyboard.GetState(); if (keyboardState.IsKeyDown(Keys.Up)) { Position.Y -= (float)(Speed * gameTime.ElapsedGameTime.TotalMilliseconds); direction = Direction.Up; } if (keyboardState.IsKeyDown(Keys.Down)) { Position.Y += (float)(Speed * gameTime.ElapsedGameTime.TotalMilliseconds); direction = Direction.Down; } if (keyboardState.IsKeyDown(Keys.Right)) { Position.X += (float)(Speed * gameTime.ElapsedGameTime.TotalMilliseconds); direction = Direction.Right; } if (keyboardState.IsKeyDown(Keys.Left)) { Position.X -= (float)(Speed * gameTime.ElapsedGameTime.TotalMilliseconds); direction = Direction.Left; } if (PlayerRectangle.Intersects(BoxRectangle)) { if (direction == Direction.Right) Position.X = BoxRectangle.Left - PlayerRectangle.Width; else if (direction == Direction.Left) Position.X = BoxRectangle.Right; if (direction == Direction.Down) Position.Y = BoxRectangle.Top - PlayerRectangle.Height; else if (direction == Direction.Up) Position.Y = BoxRectangle.Bottom; } PlayerRectangle = new Rectangle((int)Position.X, (int)Position.Y, (int)32, (int)32); base.Update(gameTime); }

    Read the article

  • default xna 4.0 gametime don´t works well for 2D physics

    - by EusKoder
    I am developing a game using Visual Studio 2010 and XNA 4.0, after advancing to some extent with the project (a platform based 2d platformer msdn starter kit) I got to test it on different computers with different hardware (CPU, graphics, etc.) and I found that the speed of movement object of the game is quite different, I implemented the PSK physics msdn that are based on time, /// <summary> /// Updates the player's velocity and position based on input, gravity, etc. /// </summary> public void ApplyPhysics(GameTime gameTime) { float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds; Vector2 previousPosition = Position; // Base velocity is a combination of horizontal movement control and // acceleration downward due to gravity. velocity.X += movement * MoveAcceleration * elapsed; velocity.Y = MathHelper.Clamp(velocity.Y + GravityAcceleration * elapsed, -MaxFallSpeed, MaxFallSpeed); velocity.Y = DoJump(velocity.Y, gameTime); // Apply pseudo-drag horizontally. if (IsOnGround) velocity.X *= GroundDragFactor; else velocity.X *= GroundDragFactor; //velocity.X *= AirDragFactor; // Prevent the player from running faster than his top speed. velocity.X = MathHelper.Clamp(velocity.X, -MaxMoveSpeed, MaxMoveSpeed); // Apply velocity. Position += velocity *elapsed; Position = new Vector2((float)Math.Round(Position.X), (float)Math.Round(Position.Y)); // If the player is now colliding with the level, separate them. HandleCollisions(gameTime); // If the collision stopped us from moving, reset the velocity to zero. if (Position.X == previousPosition.X) velocity.X = 0; if (Position.Y == previousPosition.Y) { velocity.Y = 0; jumpTime = 0.0f; } } tested eg with a PC (PC1) 2.13GHz Intel Core 2 6400 / ATI Radeon HD 4670 and another one: (pc2) 3.00GHz Intel Pentium D / Intel 82945G Express Chipset Family by displacement difference (moving x axis at supossed (position = velocity * gametime.ElapsedGameTime.TotalSeconds) constant velocity, for example) is 3 seconds in a total of 20 (example: moving pc1 player sprite 6000 pixels in the x-axis at 20 seconds and pc 2 runs the same distance in 17 ). Tested on a 3rd PC: i72700k / Gigabyte GTX 560 TI the results are even worse, after some time after starting the game gets like 3 times slower and showing the number of pixels in each frame moved in a debug window in the game (counting updatespersecond with counter variable for updates cuantity and gametime for counting a second show 63fps), it appears as if the number is always constant ( refreshments lose the Update method?). In this pc if I put the game in fullscreen during the course of the game, the effect of "go slow" is immediate and restore window mode sometimes yield returns to "normal" and sometimes not. Eventually I began to try a new project to test whether the movement is constant in different pc loading only one sprite and its position value in screen printing. Occur The same. I even tried moving a constant amount of pixels explicitly (position + = 5) and different speeds in different pc quantities of pixels moved in x time. I have the game loop as the default (fixedTimeStep=true;SynchronizeWithVerticalRetrace=true;). I've also tried turning off and creating another timestep as discussed in different post (eg http://gafferongames.com/game-physics/fix-your-timestep/ but i can´t achieve the desired result, move the same number of pixels in X seconds on different computers with windows. All pc used for tests use windows 7 enterprise pc1 == x86 the others are x64. The weirdest thing is that I find information about people describing the same problem and that I wear long nights of searches. Thanks for your help.

    Read the article

  • Inverted textures

    - by brainydexter
    I'm trying to draw textures aligned with this physics body whose coordinate system's origin is at the center of the screen. (XNA)Spritebatch has its default origin set to top-left corner. I got the textures to be positioned correctly, but I noticed my textures are vertically inverted. That is, an arrow texture pointing Up , when rendered points down. I'm not sure where I am going wrong with the math. My approach is to convert everything in physic's meter units and draw accordingly. Matrix proj = Matrix.CreateOrthographic(scale * graphics.GraphicsDevice.Viewport.AspectRatio, scale, 0, 1); Matrix view = Matrix.Identity; effect.World = Matrix.Identity; effect.View = view; effect.Projection = proj; effect.TextureEnabled = true; effect.VertexColorEnabled = true; effect.Techniques[0].Passes[0].Apply(); SpriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, DepthStencilState.Default, RasterizerState.CullNone, effect); m_Paddles[1].Draw(gameTime); SpriteBatch.End(); where Paddle::Draw looks like: SpriteBatch.Draw(paddleTexture, mBody.Position, null, Color.White, 0f, new Vector2(16f, 16f), // origin of the texture 0.1875f, SpriteEffects.None, // width of box is 3*2 = 6 meters. texture is 32 pixels wide. to make it 6 meters wide in world space: 6/32 = 0.1875f 0); The orthographic projection matrix seem fine to me, but I am obviously doing something wrong somewhere! Can someone please help me figure out what am i doing wrong here ? Thanks

    Read the article

  • How does flocking algorithm work?

    - by Chan
    I read and understand the basic of flocking algorithm. Basically, we need to have 3 behaviors: 1. Cohesion 2. Separation 3. Alignment From my understanding, it's like a state machine. Every time we do an update (then draw), we check all the constraints on both three behaviors. And each behavior returns a Vector3 which is the "correct" orientation that an object should transform to. So my initial idea was /// <summary> /// Objects stick together /// </summary> /// <returns></returns> private Vector3 Cohesion() { Vector3 result = new Vector3(0.0f, 0.0f, 0.0f); return result; } /// <summary> /// Object align /// </summary> /// <returns></returns> private Vector3 Align() { Vector3 result = new Vector3(0.0f, 0.0f, 0.0f); return result; } /// <summary> /// Object separates from each others /// </summary> /// <returns></returns> private Vector3 Separate() { Vector3 result = new Vector3(0.0f, 0.0f, 0.0f); return result; } Then I search online for pseudocode but many of them involve velocity and acceleration plus other stuffs. This part confused me. In my game, all objects move at constant speed, and they have one leader. So can anyone share me an idea how to start on implement this flocking algorithm? Also, did I understand it correctly? (I'm using XNA 4.0)

    Read the article

  • Managing game state / 'what to update' within an XNA game 'screen'

    - by codinghands
    Note - having read through other GDev questions suggested when writing this question I'm confident this isn't a dupe. Of course, it's 3am and I'm likely wrong, so please mod as such if so. I'm trying to figure out how best to manage state within my game screens - please bare with me though! At the moment I'm using a heavily modified version of the fantastic game state management example on the XNA site available here. This is working perfectly for my 'Screens' - 'IntroScreen' with some shiny logos, 'TitleScreen' and a 'MenuScreen' stacked on top for the title and menu, 'PlayScreen' for the actual gameplay, etc. Each screen has the a bunch of sprites, and an 'Update' and 'Draw', managed by a 'ScreenManager'. In addition to the above, and as suggested as an answer to my other question here, most screens have a 'GameProcessQueue' class full of 'GameProcess'es which lets me do just about anything (animations, youbetcha!), in any order, in sequence or parallel. Why mention all this? When I talk about managing game state I'm thinking more for complex scenarios within a 'Screen'. 'TitleScreen', 'MenuScreen' and the like are all relatively simple. 'Play Screen' less so. How do people manage the different 'states' within the screen (or whatever you call it) that 'does' gameplay? (for me, the 'PlayScreen') I've thought about the following: Enum of different states in the Screen, 'activeState' enum-type variable, switching on the enum in the Screen Update() loop to determine what Screen Update 'sub'-function is called. I can see this getting hairy pretty fast though as screens get more complex and with the 'PlayScreen' becoming a behemoth mega-class. 'State' class with Update loop - a Screen can have any number of 'States', 1+ of which are 'active'. Screen update loop calls update on all active states. States themselves know which screen they belong to, and may even belong to a 'StateManager' which handles transitioning from one state to the next. Once a state is over it's removed from the ScreenState list. The Screen doesn't need a bunch of GameProcessQueues, each State has its own. Abstract Screen further to be more flexible - I can see the similarities between what I've got (game 'Screens' handled by a ScreenManager) and what I want (states within a screen, and a mechanism to manage them). However at the moment I see 'Screens' as high level and very distinct ('PlayScreen' with baddies != 'MenuScreen' with 4 words and event handlers), where as my proposed 'States' are more intrinsically tied to a specific screen with complex requirements. I think. This is for a turn-based board game, so it's easier to define things as a discrete series of steps (IntroAnimation - P1Turn - P2Turn - P1Turn ... - GameOver - .... Obviously with an open-world RPG things are very different, but any advice in this scenario is appreciated. If I'm just going OOP-crazy please say so. Similarly I'm concious there's a huge amount on this site re: state management. But as my first 'serious' game after a couple of false starts I'd like to get this right, and would rather be harassed and modded down than never ask :)

    Read the article

  • Collision with half semi-circle

    - by heitortsergent
    I am trying to port a game I made using Flash/AS3, to the Windows Phone using C#/XNA 4.0. You can see it here: http://goo.gl/gzFiE In the flash version I used a pixel-perfect collision between meteors (it's a rectangle, and usually rotated) that spawn outside the screen, and move towards the center, and a shield in the center of the screen(which is half of a semi-circle, also rotated by the player), which made the meteor bounce back in the opposite direction it came from, when they collided. My goal now is to make the meteors bounce in different angles, depending on the position it collides with the shield (much like Pong, hitting the borders causes a change in the ball's angle). So, these are the 3 options I thought of: -Pixel-perfect collision (microsoft has a sample(http://create.msdn.com/en-US/education/catalog/tutorial/collision_2d_perpixel_transformed)) , but then I wouldn't know how to change the meteor angle after the collision -3 BoundingCircle's to represent the half semi-circle shield, but then I would have to somehow move them as I rotate the shield. -Farseer Physics. I could make a shape composed of 3 lines, and use that as the collision object for the shield. Is there any other way besides those? Which would be the best way to do it(it's aimed towards mobile devices, so pixel-perfect is probably not a good choice)? Most of the time there's always a easier/better way than what we think of...

    Read the article

  • Collision with half of a semi-circle

    - by heitortsergent
    I am trying to port a game I made using Flash/AS3, to the Windows Phone using C#/XNA 4.0. You can see it here: http://goo.gl/gzFiE In the flash version I used a pixel-perfect collision between meteors (it's a rectangle, and usually rotated) that spawn outside the screen, and move towards the center, and a shield in the center of the screen(which is half of a semi-circle, also rotated by the player), which made the meteor bounce back in the opposite direction it came from, when they collided. My goal now is to make the meteors bounce in different angles, depending on the position it collides with the shield (much like Pong, hitting the borders causes a change in the ball's angle). So, these are the 3 options I thought of: Pixel-perfect collision (Microsoft has a sample) , but then I wouldn't know how to change the meteor angle after the collision 3 BoundingCircle's to represent the half semi-circle shield, but then I would have to somehow move them as I rotate the shield. Farseer Physics. I could make a shape composed of 3 lines, and use that as the collision object for the shield. Is there any other way besides those? Which would be the best way to do it(it's aimed towards mobile devices, so pixel-perfect is probably not a good choice)? Most of the time there's always a easier/better way than what we think of...

    Read the article

  • Set a 2d camera's position so that a building is under the players feet

    - by Potato
    My issue is this: i am making a scrolling game in XNA, and the camera updates based on the players velocity, but the player never actually moves, he is always in the center of the screen. When he hits the top of the building though i want him to always be on top and sink through the texture in a way like this: what i am doing to make this happen is i am just setting his velocity to 0, so its not moving, but the more velocity he hits a building with the more he sinks through it. I also tried setting the buildings position to the plays Bounding Box's bottom, and this achieved the look i wanted but this also resulted in the other buildings rising in the air, because the velocity was still moving (even if i set it to 0). if it was not a scrolling game, this would be not a problem, because you just set the players position to the top of the building, but because the player never actually moves, i actually need to move the camera to the point where the building is under the players feet without the other buildings rising. (Take note this is note a real camera, it is just a class that moves the objects in the world based on the players velocity). All questions are welcome.

    Read the article

  • Unable to create suitable graphics device?

    - by kraze
    I've been following the Eye of the Dragon tutorial, which is basicly a guide to making a 2D RPG game, obviously. I recently finished the tutorial about making pop up screens in the menu and changed the screen to load as a full screen. Whenever I try and load the game it just goes black and my mouse sits there. I cannot change out of it other then with CtrlAltDel. Once i do that it says No suitable graphics card found, unable to create graphics device. I read somewhere about XNA not allowing more then one screen when any one of them is full screen. but it wasnt very informative. Anyone have any ideas whats going on and/or how to fix this? Just incase if this helps this is the code for the graphics device: public Game1() { graphics = new GraphicsDeviceManager(this); graphics.PreferredBackBufferWidth = 900; graphics.PreferredBackBufferHeight = 768; graphics.IsFullScreen = true; this.Window.Title = "Eyes of the Dragon"; Content.RootDirectory = "Content"; }

    Read the article

  • XNA WP7 Texture memory and ContentManager

    - by jlongstreet
    I'm trying to get my WP7 XNA game's memory under control and under the 90MB limit for submission. One target I identified was UI textures, especially fullscreen ones, that would never get unloaded. So I moved UI texture loads to their own ContentManager so I can unload them. However, this doesn't seem to affect the value of Microsoft.Phone.Info.DeviceExtendedProperties.GetValue("ApplicationCurrentMemoryUsage"), so it doesn't look like the memory is actually being released. Example: splash screens. In Game.LoadContent(): Application.Instance.SetContentManager("UI"); // set the current content manager for (int i = 0; i < mSplashTextures.Length; ++i) { // load the splash textures mSplashTextures[i] = Application.Instance.Content.Load<Texture2D>(msSplashTextureNames[i]); } // set the content manager back to the global one Application.Instance.SetContentManager("Global"); When the initial load is done and the title screen starts, I do: Application.Instance.GetContentManager("UI").Unload(); The three textures take about 6.5 MB of memory. Before unloading the UI ContentManager, I see that ApplicationCurrentMemoryUsage is at 34.29 MB. After unloading the ContentManager (and doing a full GC.Collect()), it's still at 34.29 MB. But after that, I load another fullscreen texture (for the title screen background) and memory usage still doesn't change. Could it be keeping the memory for these textures allocated and reusing it? edit: very simple test: protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); PrintMemUsage("Before texture load: "); // TODO: use this.Content to load your game content here red = this.Content.Load<Texture2D>("Untitled"); PrintMemUsage("After texture load: "); } private void PrintMemUsage(string tag) { Debug.WriteLine(tag + Microsoft.Phone.Info.DeviceExtendedProperties.GetValue("ApplicationCurrentMemoryUsage")); } protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); // TODO: Add your update logic here if (count++ == 100) { GC.Collect(); GC.WaitForPendingFinalizers(); PrintMemUsage("Before CM unload: "); this.Content.Dispose(); GC.Collect(); GC.WaitForPendingFinalizers(); PrintMemUsage("After CM unload: "); red = null; spriteBatch.Dispose(); GC.Collect(); GC.WaitForPendingFinalizers(); PrintMemUsage("After SpriteBatch Dispose(): "); } base.Update(gameTime); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); // TODO: Add your drawing code here if (red != null) { spriteBatch.Begin(); spriteBatch.Draw(red, new Vector2(0,0), Color.White); spriteBatch.End(); } base.Draw(gameTime); } This prints something like (it changes every time): Before texture load: 7532544 After texture load: 10727424 Before CM unload: 9875456 After CM unload: 9953280 After SpriteBatch Dispose(): 9953280

    Read the article

  • What is the future of XNA in Windows 8 or how will manged games be developed in Windows 8?

    - by Ken
    I know this is a potential dupe of this question, but the last answer there was 18 months ago and a lot has happened since. There seems to be some uncertainty about XNA in Windows 8. Specifically, Windows 8 by default uses the Metro interface, which is not supported by XNA. Also the Windows 8 store will not stock non-metro apps, so it will not stock XNA apps. Should we stick with XNA or does Microsoft want us to move to a different framework for managed game development in Windows 8? Edit: As pointed out in one of the comments, Windows 8 will be able to run XNA games in a backward compatibility mode. But that smells of deprecation.

    Read the article

  • XNA RTS A* pathfinding issues

    - by Slayter
    I'm starting to develop an RTS game using the XNA framework in C# and am still in the very early prototyping stage. I'm working on the basics. I've got unit selection down and am currently working on moving multiple units. I've implemented an A* pathfinding algorithm which works fine for moving a single unit. However when moving multiple units they stack on top of each other. I tried fixing this with a variation of the boids flocking algorithm but this has caused units to sometimes freeze and get stuck trying to move but going no where. Ill post the related methods for moving the units below but ill only post a link to the pathfinding class because its really long and i don't want to clutter up the page. These parts of the code are in the update method for the main controlling class: if (selectedUnits.Count > 0) { int indexOfLeader = 0; for (int i = 0; i < selectedUnits.Count; i++) { if (i == 0) { indexOfLeader = 0; } else { if (Vector2.Distance(selectedUnits[i].position, destination) < Vector2.Distance(selectedUnits[indexOfLeader].position, destination)) indexOfLeader = i; } selectedUnits[i].leader = false; } selectedUnits[indexOfLeader].leader = true; foreach (Unit unit in selectedUnits) unit.FindPath(destination); } foreach (Unit unit in units) { unit.Update(gameTime, selectedUnits); } These three methods control movement in the Unit class: public void FindPath(Vector2 destination) { if (path != null) path.Clear(); Point startPoint = new Point((int)position.X / 32, (int)position.Y / 32); Point endPoint = new Point((int)destination.X / 32, (int)destination.Y / 32); path = pathfinder.FindPath(startPoint, endPoint); pointCounter = 0; if (path != null) nextPoint = path[pointCounter]; dX = 0.0f; dY = 0.0f; stop = false; } private void Move(List<Unit> units) { if (nextPoint == position && !stop) { pointCounter++; if (pointCounter <= path.Count - 1) { nextPoint = path[pointCounter]; if (nextPoint == position) stop = true; } else if (pointCounter >= path.Count) { path.Clear(); pointCounter = 0; stop = true; } } else { if (!stop) { map.occupiedPoints.Remove(this); Flock(units); // Move in X ********* TOOK OUT SPEED ********** if ((int)nextPoint.X > (int)position.X) { position.X += dX; } else if ((int)nextPoint.X < (int)position.X) { position.X -= dX; } // Move in Y if ((int)nextPoint.Y > (int)position.Y) { position.Y += dY; } else if ((int)nextPoint.Y < (int)position.Y) { position.Y -= dY; } if (position == nextPoint && pointCounter >= path.Count - 1) stop = true; map.occupiedPoints.Add(this, position); } if (stop) { path.Clear(); pointCounter = 0; } } } private void Flock(List<Unit> units) { float distanceToNextPoint = Vector2.Distance(position, nextPoint); foreach (Unit unit in units) { float distance = Vector2.Distance(position, unit.position); if (unit != this) { if (distance < space && !leader && (nextPoint != position)) { // create space dX += (position.X - unit.position.X) * 0.1f; dY += (position.Y - unit.position.Y) * 0.1f; if (dX > .05f) nextPoint.X = nextPoint.X - dX; else if (dX < -.05f) nextPoint.X = nextPoint.X + dX; if (dY > .05f) nextPoint.Y = nextPoint.Y - dY; else if (dY < -.05f) nextPoint.Y = nextPoint.Y + dY; if ((dX < .05f && dX > -.05f) && (dY < .05f && dY > -.05f)) stop = true; path[pointCounter] = nextPoint; Console.WriteLine("Make Space: " + dX + ", " + dY); } else if (nextPoint != position && !stop) { dX = speed; dY = speed; Console.WriteLine(dX + ", " + dY); } } } } And here's the link to the pathfinder: https://docs.google.com/open?id=0B_Cqt6txUDkddU40QXBMeTR1djA I hope this post wasn't too long. Also please excuse the messiness of the code. As I said before this is early prototyping. Any help would be appreciated. Thanks!

    Read the article

  • Collision Detection problems in Voxel Engine (XNA)

    - by Darestium
    I am creating a minecraft like terrain engine in XNA and have had some collision problems for quite some time. I have checked and changed my code based on other peoples collision code and I still have the same problem. It always seems to be off by about a block. for instance, if I walk across a bridge which is one block high I fall through it. Also, if you walk towards a "row" of blocks like this: You are able to stand "inside" the left most one, and you collide with nothing in the right most side (where there is no block and is not visible on this image). Here is all my collision code: private void Move(GameTime gameTime, Vector3 direction) { float speed = playermovespeed * (float)gameTime.ElapsedGameTime.TotalSeconds; Matrix rotationMatrix = Matrix.CreateRotationY(player.Camera.LeftRightRotation); Vector3 rotatedVector = Vector3.Transform(direction, rotationMatrix); rotatedVector.Normalize(); Vector3 testVector = rotatedVector; testVector.Normalize(); Vector3 movePosition = player.position + testVector * speed; Vector3 midBodyPoint = movePosition + new Vector3(0, -0.7f, 0); Vector3 headPosition = movePosition + new Vector3(0, 0.1f, 0); if (!world.GetBlock(movePosition).IsSolid && !world.GetBlock(midBodyPoint).IsSolid && !world.GetBlock(headPosition).IsSolid) { player.position += rotatedVector * speed; } //player.position += rotatedVector * speed; } ... public void UpdatePosition(GameTime gameTime) { player.velocity.Y += playergravity * (float)gameTime.ElapsedGameTime.TotalSeconds; Vector3 footPosition = player.Position + new Vector3(0f, -1.5f, 0f); Vector3 headPosition = player.Position + new Vector3(0f, 0.1f, 0f); // If the block below the player is solid the Y velocity should be zero if (world.GetBlock(footPosition).IsSolid || world.GetBlock(headPosition).IsSolid) { player.velocity.Y = 0; } UpdateJump(gameTime); UpdateCounter(gameTime); ProcessInput(gameTime); player.Position = player.Position + player.velocity * (float)gameTime.ElapsedGameTime.TotalSeconds; velocity = Vector3.Zero; } and the one and only function in the camera class: protected void CalculateView() { Matrix rotationMatrix = Matrix.CreateRotationX(upDownRotation) * Matrix.CreateRotationY(leftRightRotation); lookVector = Vector3.Transform(Vector3.Forward, rotationMatrix); cameraFinalTarget = Position + lookVector; Vector3 cameraRotatedUpVector = Vector3.Transform(Vector3.Up, rotationMatrix); viewMatrix = Matrix.CreateLookAt(Position, cameraFinalTarget, cameraRotatedUpVector); } which is called when the rotation variables are changed: public float LeftRightRotation { get { return leftRightRotation; } set { leftRightRotation = value; CalculateView(); } } public float UpDownRotation { get { return upDownRotation; } set { upDownRotation = value; CalculateView(); } } World class: public Block GetBlock(int x, int y, int z) { if (InBounds(x, y, z)) { Vector3i regionalPosition = GetRegionalPosition(x, y, z); Vector3i region = GetRegionPosition(x, y, z); return regions[region.X, region.Y, region.Z].Blocks[regionalPosition.X, regionalPosition.Y, regionalPosition.Z]; } return new Block(BlockType.none); } public Vector3i GetRegionPosition(int x, int y, int z) { int regionx = x == 0 ? 0 : x / Variables.REGION_SIZE_X; int regiony = y == 0 ? 0 : y / Variables.REGION_SIZE_Y; int regionz = z == 0 ? 0 : z / Variables.REGION_SIZE_Z; return new Vector3i(regionx, regiony, regionz); } public Vector3i GetRegionalPosition(int x, int y, int z) { int regionx = x == 0 ? 0 : x / Variables.REGION_SIZE_X; int X = x % Variables.REGION_SIZE_X; int regiony = y == 0 ? 0 : y / Variables.REGION_SIZE_Y; int Y = y % Variables.REGION_SIZE_Y; int regionz = z == 0 ? 0 : z / Variables.REGION_SIZE_Z; int Z = z % Variables.REGION_SIZE_Z; return new Vector3i(X, Y, Z); } Any ideas how to fix this problem? EDIT 1: Graphic of the problem: EDIT 2 GetBlock, Vector3 version: public Block GetBlock(Vector3 position) { int x = (int)Math.Floor(position.X); int y = (int)Math.Floor(position.Y); int z = (int)Math.Ceiling(position.Z); Block block = GetBlock(x, y, z); return block; } Now, the thing is I tested the theroy that the Z is always "off by one" and by ceiling the value it actually works as intended. Altough it still could be greatly more accurate (when you go down holes you can see through the sides, and I doubt it will work with negitive positions). I also does not feel clean Flooring the X and Y values and just Ceiling the Z. I am surely not doing something correctly still.

    Read the article

  • C# XNA 4.0 multitextured cube

    - by chron
    So I am following this tutorial on how to draw a cube in XNA and I ran into a problem. Ok so my shader can only have texture right? I need to have a texture on the front and back of my cube. So I thought I could just have both textures stored in one texture. Problem is I do not know how to map out my UV coords to do so. (I tried dividing by 2 and such with no luck...). I am really new to this (not programming, just game development and some concepts), but how could I get UV coordinates for both halfs of the texture. private void ConstructCube(Vector3 Position,Vector3 Size) { _vertices = new VertexPositionNormalTexture[50]; // Calculate the position of the vertices on the top face. Vector3 topLeftFront = Position + new Vector3(-1.0f, 1.0f, -1.0f) * Size; Vector3 topLeftBack = Position + new Vector3(-1.0f, 1.0f, 1.0f) * Size; Vector3 topRightFront = Position + new Vector3(1.0f, 1.0f, -1.0f) * Size; Vector3 topRightBack = Position + new Vector3(1.0f, 1.0f, 1.0f) * Size; // Calculate the position of the vertices on the bottom face. Vector3 btmLeftFront = Position + new Vector3(-1.0f, -1.0f, -1.0f) * Size; Vector3 btmLeftBack = Position + new Vector3(-1.0f, -1.0f, 1.0f) * Size; Vector3 btmRightFront = Position + new Vector3(1.0f, -1.0f, -1.0f) * Size; Vector3 btmRightBack = Position + new Vector3(1.0f, -1.0f, 1.0f) * Size; // Normal vectors for each face (needed for lighting / display) Vector3 normalFront = new Vector3(0.0f, 0.0f, 1.0f) * Size; Vector3 normalBack = new Vector3(0.0f, 0.0f, -1.0f) * Size; Vector3 normalTop = new Vector3(0.0f, 1.0f, 0.0f) * Size; Vector3 normalBottom = new Vector3(0.0f, -1.0f, 0.0f) * Size; Vector3 normalLeft = new Vector3(-1.0f, 0.0f, 0.0f) * Size; Vector3 normalRight = new Vector3(1.0f, 0.0f, 0.0f) * Size; // UV texture coordinates Vector2 textureTopLeft = new Vector2(1.0f * Size.X, 0.0f * Size.Y); Vector2 textureTopRight = new Vector2(0.0f * Size.X, 0.0f * Size.Y); Vector2 textureBottomLeft = new Vector2(1.0f * Size.X, 1.0f * Size.Y); Vector2 textureBottomRight = new Vector2(0.0f * Size.X, 1.0f * Size.Y); // Add the vertices for the FRONT face. _vertices[0] = new VertexPositionNormalTexture(topLeftFront, normalFront, textureTopLeft); _vertices[1] = new VertexPositionNormalTexture(btmLeftFront, normalFront, textureBottomLeft); _vertices[2] = new VertexPositionNormalTexture(topRightFront, normalFront, textureTopRight); _vertices[3] = new VertexPositionNormalTexture(btmLeftFront, normalFront, textureBottomLeft); _vertices[4] = new VertexPositionNormalTexture(btmRightFront, normalFront, textureBottomRight); _vertices[5] = new VertexPositionNormalTexture(topRightFront, normalFront, textureTopRight); // Add the vertices for the BACK face. _vertices[6] = new VertexPositionNormalTexture(topLeftBack, normalBack, textureTopRight); _vertices[7] = new VertexPositionNormalTexture(topRightBack, normalBack, textureTopLeft); _vertices[8] = new VertexPositionNormalTexture(btmLeftBack, normalBack, textureBottomRight); _vertices[9] = new VertexPositionNormalTexture(btmLeftBack, normalBack, textureBottomRight); _vertices[10] = new VertexPositionNormalTexture(topRightBack, normalBack, textureTopLeft); _vertices[11] = new VertexPositionNormalTexture(btmRightBack, normalBack, textureBottomLeft); // Add the vertices for the TOP face. _vertices[12] = new VertexPositionNormalTexture(topLeftFront, normalTop, textureBottomLeft); _vertices[13] = new VertexPositionNormalTexture(topRightBack, normalTop, textureTopRight); _vertices[14] = new VertexPositionNormalTexture(topLeftBack, normalTop, textureTopLeft); _vertices[15] = new VertexPositionNormalTexture(topLeftFront, normalTop, textureBottomLeft); _vertices[16] = new VertexPositionNormalTexture(topRightFront, normalTop, textureBottomRight); _vertices[17] = new VertexPositionNormalTexture(topRightBack, normalTop, textureTopRight); // Add the vertices for the BOTTOM face. _vertices[18] = new VertexPositionNormalTexture(btmLeftFront, normalBottom, textureTopLeft); _vertices[19] = new VertexPositionNormalTexture(btmLeftBack, normalBottom, textureBottomLeft); _vertices[20] = new VertexPositionNormalTexture(btmRightBack, normalBottom, textureBottomRight); _vertices[21] = new VertexPositionNormalTexture(btmLeftFront, normalBottom, textureTopLeft); _vertices[22] = new VertexPositionNormalTexture(btmRightBack, normalBottom, textureBottomRight); _vertices[23] = new VertexPositionNormalTexture(btmRightFront, normalBottom, textureTopRight); // Add the vertices for the LEFT face. _vertices[24] = new VertexPositionNormalTexture(topLeftFront, normalLeft, textureTopRight); _vertices[25] = new VertexPositionNormalTexture(btmLeftBack, normalLeft, textureBottomLeft ); _vertices[26] = new VertexPositionNormalTexture(btmLeftFront, normalLeft, textureBottomRight ); _vertices[27] = new VertexPositionNormalTexture(topLeftBack, normalLeft, textureTopLeft); _vertices[28] = new VertexPositionNormalTexture(btmLeftBack, normalLeft, textureBottomLeft ); _vertices[29] = new VertexPositionNormalTexture(topLeftFront, normalLeft, textureTopRight ); // Add the vertices for the RIGHT face. _vertices[30] = new VertexPositionNormalTexture(topRightFront, normalRight, textureTopLeft); _vertices[31] = new VertexPositionNormalTexture(btmRightFront, normalRight, textureBottomLeft); _vertices[32] = new VertexPositionNormalTexture(btmRightBack, normalRight, textureBottomRight); _vertices[33] = new VertexPositionNormalTexture(topRightBack, normalRight, textureTopRight); _vertices[34] = new VertexPositionNormalTexture(topRightFront, normalRight, textureTopLeft); _vertices[35] = new VertexPositionNormalTexture(btmRightBack, normalRight, textureBottomRight); done = true; }

    Read the article

  • Shuffle tiles position in the beginning of the game XNA Csharp

    - by GalneGunnar
    Im trying to create a puzzlegame where you move tiles to certain positions to make a whole image. I need help with randomizing the tiles startposition so that they don't create the whole image at the beginning. There is also something wrong with my offset, that's why it's set to (0,0). I know my code is not good, but Im just starting to learn :] Thanks in advance My Game1 class: { public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; Texture2D PictureTexture; Texture2D FrameTexture; // Offset för bildgraff Vector2 Offset = new Vector2(0,0); //skapar en array som ska hålla delar av den stora bilden Square[,] squareArray = new Square[4, 4]; // Random randomeraBilder = new Random(); //Width och Height för bilden int pictureHeight = 95; int pictureWidth = 144; Random randomera = new Random(); int index = 0; MouseState oldMouseState; int WindowHeight; int WindowWidth; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; //scalar Window till 800x 600y graphics.PreferredBackBufferWidth = 800; graphics.PreferredBackBufferHeight = 600; graphics.ApplyChanges(); } protected override void Initialize() { IsMouseVisible = true; base.Initialize(); } protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); PictureTexture = Content.Load<Texture2D>(@"Images/bildgraff"); FrameTexture = Content.Load<Texture2D>(@"Images/framer"); //Laddar in varje liten bild av den stora bilden i en array for (int x = 0; x < 4; x++) { for (int y = 0; y < 4; y++) { Vector2 position = new Vector2(x * pictureWidth, y * pictureHeight); position = position + Offset; Rectangle square = new Rectangle(x * pictureWidth, y * pictureHeight, pictureWidth, pictureHeight); Square frame = new Square(position, PictureTexture, square, Offset, index); squareArray[x, y] = frame; index++; } } } protected override void UnloadContent() { } protected override void Update(GameTime gameTime) { if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); MouseState ms = Mouse.GetState(); if (oldMouseState.LeftButton == ButtonState.Pressed && ms.LeftButton == ButtonState.Released) { // ta reda på vilken position vi har tryckt på int col = ms.X / pictureWidth; int row = ms.Y / pictureHeight; for (int x = 0; x < squareArray.GetLength(0); x++) { for (int y = 0; y < squareArray.GetLength(1); y++) { // kollar om rutan är tom och så att indexet inte går utanför för "col" och "row" if (squareArray[x, y].index == 0 && col >= 0 && row >= 0 && col <= 3 && row <= 3) { if (squareArray[x, y].index == 0 * col) { //kollar om rutan brevid mouseclick är tom if (col > 0 && squareArray[col - 1, row].index == 0 || row > 0 && squareArray[col, row - 1].index == 0 || col < 3 && squareArray[col + 1, row].index == 0 || row < 3 && squareArray[col, row + 1].index == 0) { Square sqaure = squareArray[col, row]; Square hal = squareArray[x, y]; squareArray[x, y] = sqaure; squareArray[col, row] = hal; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { Vector2 goalPosition = new Vector2(x * pictureWidth, y * pictureHeight); squareArray[x, y].Swap(goalPosition); } } } } } } } } //if (oldMouseState.RightButton == ButtonState.Pressed && ms.RightButton == ButtonState.Released) //{ // for (int x = 0; x < 4; x++) // { // for (int y = 0; y < 4; y++) // { // } // } //} oldMouseState = ms; base.Update(gameTime); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); WindowHeight = Window.ClientBounds.Height; WindowWidth = Window.ClientBounds.Width; Rectangle screenPosition = new Rectangle(0,0, WindowWidth, WindowHeight); spriteBatch.Begin(); spriteBatch.Draw(FrameTexture, screenPosition, Color.White); //Ritar ut alla brickorna förutom den som har index 0 for (int x = 0; x < 4; x++) { for (int y = 0; y < 4; y++) { if (squareArray[x, y].index != 0) { squareArray[x, y].Draw(spriteBatch); } } } spriteBatch.End(); base.Draw(gameTime); } } } My square class: class Square { public Vector2 position; public Texture2D grafTexture; public Rectangle square; public Vector2 offset; public int index; public Square(Vector2 position, Texture2D grafTexture, Rectangle square, Vector2 offset, int index) { this.position = position; this.grafTexture = grafTexture; this.square = square; this.offset = offset; this.index = index; } public void Draw(SpriteBatch spritebatch) { spritebatch.Draw(grafTexture, position, square, Color.White); } public void RandomPosition() { } public void Swap(Vector2 Goal ) { if (Goal.X > position.X) { position.X = position.X + 144; } else if (Goal.X < position.X) { position.X = position.X - 144; } else if (Goal.Y < position.Y) { position.Y = position.Y - 95; } else if (Goal.Y > position.Y) { position.Y = position.Y + 95; } } } }

    Read the article

  • How do I calculate the boundary of the game window after transforming the view?

    - by Cypher
    My Camera class handles zoom, rotation, and of course panning. It's invoked through SpriteBatch.Begin, like so many other XNA 2D camera classes. It calculates the view Matrix like so: public Matrix GetViewMatrix() { return Matrix.Identity * Matrix.CreateTranslation(new Vector3(-this.Spatial.Position, 0.0f)) * Matrix.CreateTranslation(-( this.viewport.Width / 2 ), -( this.viewport.Height / 2 ), 0.0f) * Matrix.CreateRotationZ(this.Rotation) * Matrix.CreateScale(this.Scale, this.Scale, 1.0f) * Matrix.CreateTranslation(this.viewport.Width * 0.5f, this.viewport.Height * 0.5f, 0.0f); } I was having a minor issue with performance, which after doing some profiling, led me to apply a culling feature to my rendering system. It used to, before I implemented the camera's zoom feature, simply grab the camera's boundaries and cull any game objects that did not intersect with the camera. However, after giving the camera the ability to zoom, that no longer works. The reason why is visible in the screenshot below. The navy blue rectangle represents the camera's boundaries when zoomed out all the way (Camera.Scale = 0.5f). So, when zoomed out, game objects are culled before they reach the boundaries of the window. The camera's width and height are determined by the Viewport properties of the same name (maybe this is my mistake? I wasn't expecting the camera to "resize" like this). What I'm trying to calculate is a Rectangle that defines the boundaries of the screen, as indicated by my awesome blue arrows, even after the camera is rotated, scaled, or panned. Here is how I've more recently found out how not to do it: public Rectangle CullingRegion { get { Rectangle region = Rectangle.Empty; Vector2 size = this.Spatial.Size; size *= 1 / this.Scale; Vector2 position = this.Spatial.Position; position = Vector2.Transform(position, this.Inverse); region.X = (int)position.X; region.Y = (int)position.Y; region.Width = (int)size.X; region.Height = (int)size.Y; return region; } } It seems to calculate the right size, but when I render this region, it moves around which will obviously cause problems. It needs to be "static", so to speak. It's also obscenely slow, which causes more of a problem than it solves. What am I missing?

    Read the article

  • 2D Particle Explosion

    - by TheBroodian
    I'm developing a 2D action game, and in said game I've given my primary character an ability he can use to throw a fireball. I'm trying to design an effect so that when said fireball collides (be it with terrain or with an enemy) that the fireball will explode. For the explosion effect I've created a particle that once placed into game space will follow random, yet autonomic behavior based on random variables. Here is my question: When I generate my explosion (essentially 90 of these particles) I get one of two behaviors, 1) They are all generated with the same random variables, and don't resemble an explosion at all, more like a large mass of clumped sprites that all follow the same randomly generated path. 2) If I assign each particle a unique seed to its random number generator, they are a little bit -more- spread out, yet clumping is still visible (they seem to fork out into 3 different directions) Does anybody have any tips for producing particle-based 2D explosions? I'll include the code for my particle and the event I'm generating them in. Fire particle class: public FireParticle(xTile.Dimensions.Location StartLocation, ContentManager content) { worldLocation = StartLocation; fireParticleAnimation = new FireParticleAnimation(content); random = new Random(); int rightorleft = random.Next(0, 3); int upordown = random.Next(1, 3); int xVelocity = random.Next(0, 101); int yVelocity = random.Next(0, 101); Vector2 tempVector2 = new Vector2(0,0); if (rightorleft == 1) { tempVector2 = new Vector2(xVelocity, tempVector2.Y); } else if (rightorleft == 2) { tempVector2 = new Vector2(-xVelocity, tempVector2.Y); } if (upordown == 1) { tempVector2 = new Vector2(tempVector2.X, -yVelocity); } else if (upordown == 2) { tempVector2 = new Vector2(tempVector2.X, yVelocity); } velocity = tempVector2; scale = random.Next(1, 11); upwardForce = -10; dead = false; } public FireParticle(xTile.Dimensions.Location StartLocation, ContentManager content, int seed) { worldLocation = StartLocation; fireParticleAnimation = new FireParticleAnimation(content); random = new Random(seed); int rightorleft = random.Next(0, 3); int upordown = random.Next(1, 3); int xVelocity = random.Next(0, 101); int yVelocity = random.Next(0, 101); Vector2 tempVector2 = new Vector2(0, 0); if (rightorleft == 1) { tempVector2 = new Vector2(xVelocity, tempVector2.Y); } else if (rightorleft == 2) { tempVector2 = new Vector2(-xVelocity, tempVector2.Y); } if (upordown == 1) { tempVector2 = new Vector2(tempVector2.X, -yVelocity); } else if (upordown == 2) { tempVector2 = new Vector2(tempVector2.X, yVelocity); } velocity = tempVector2; scale = random.Next(1, 11); upwardForce = -10; dead = false; } #endregion #region Update and Draw public void Update(GameTime gameTime) { elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds; fireParticleAnimation.Update(gameTime); Vector2 moveAmount = velocity * elapsed; xTile.Dimensions.Location newPosition = new xTile.Dimensions.Location(worldLocation.X + (int)moveAmount.X, worldLocation.Y + (int)moveAmount.Y); worldLocation = newPosition; velocity.Y += upwardForce; if (fireParticleAnimation.finishedPlaying) { dead = true; } } public void Draw(SpriteBatch spriteBatch) { spriteBatch.Draw( fireParticleAnimation.image.Image, new Rectangle((int)drawLocation.X, (int)drawLocation.Y, scale, scale), fireParticleAnimation.image.SizeAndsource, Color.White * fireParticleAnimation.image.Alpha); } Fireball explosion event: public override void Update(GameTime gameTime) { if (enabled) { float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds; foreach (Heart_of_Fire.World_Objects.Particles.FireParticle particle in explosionParticles.ToList()) { particle.Update(gameTime); if (particle.Dead) { explosionParticles.Remove(particle); } } collisionRectangle = new Microsoft.Xna.Framework.Rectangle((int)wrldPstn.X, (int)wrldPstn.Y, 5, 5); explosionCheck = exploded; if (!exploded) { coreGraphic.Update(gameTime); tailGraphic.Update(gameTime); Vector2 moveAmount = velocity * elapsed; moveAmount = horizontalCollision(moveAmount, layer); moveAmount = verticalCollision(moveAmount, layer); Vector2 newPosition = new Vector2(wrldPstn.X + moveAmount.X, wrldPstn.Y + moveAmount.Y); if (hasCollidedHorizontally || hasCollidedVertically) { exploded = true; } wrldPstn = newPosition; worldLocation = new xTile.Dimensions.Location((int)wrldPstn.X, (int)wrldPstn.Y); } if (explosionCheck != exploded) { for (int i = 0; i < 90; i++) { explosionParticles.Add(new World_Objects.Particles.FireParticle( new Location( collisionRectangle.X + random.Next(0, 6), collisionRectangle.Y + random.Next(0, 6)), contentMgr)); } } if (exploded && explosionParticles.Count() == 0) { //enabled = false; } } }

    Read the article

  • XNA for life!

    - by George Clingerman
    Or until my arm falls off at least…. I’ve been meaning to get a new tattoo for quite a while. And I wanted it to be geeky and to represent some memorable milestone in my life. So I was thinking, mulling over some various ideas, sketching some things out. And then it hit me. XNA. Specifically the XNA logo. It’s super geeky (so geeky I’ll probably have to explain to 90% of the people that say it what it even means) and I’m not sure that anything has been so memorable and made such a change in my life as XNA. Cheesy but true. When the XNA framework came out, thing started happening quickly. I stumbled into a geek community and started going to code camps, MSDN events, code-a-thons. I got an XNA MVP award. Met huge geek idols in my life (like Rory Blyth and Scott Hanselman) and just really started getting integrated into this fantastic development community. Then to add to all of that I became part of this fantastic XNA community. It’s really just been one of the best things to ever happen to me and I’m having the time of my life right now. So sure, it’s permanent. Sure Microsoft could cancel XNA, rebrand it to Flimmer Flammer or some other name. Sure my arms are going to be wrinkly and flabby when I’m older and for sure I’m going to have to explain to people over and over again just what in the world “xna” means. But you know what, every time I look at that tattoo and every time I’m telling somebody what xna means, I’m going to remember all these awesome things that have happened to me. All the tremendous things I’m seeing people do with the XNA framework and more importantly all the stories and friendships I’ve formed in the XNA community. And I think that deserves a little permanent recognition.

    Read the article

  • Color sprite tint with opacity in MonoGame/XNA

    - by Piotr Walat
    In MonoGame I am using SpriteBatch to draw sprites. I want to create a semi transparent overlay that would 'tint' the sprite with a given color. SpriteBatch.Draw accepts Color parameter that allows to specify the tint, however the alpha channel seems to make the whole sprite transparent (not the tint only). To address the problem i am overlaying my sprites with another white, semitransparent sprite tinted to a given color. It works as expected, but I am not sure if that is the correct (ie. most optimal) approach. Can you suggest better/faster technique?

    Read the article

  • Cocos2d-xna memory management for WP8

    - by Arkiliknam
    I recently upgraded to VS2012 and try my in dev game out on the new WP8 emulators but was dismayed to find out the emulator now crashes and throws an out of memory exception during my sprite loading procedure (funnily, it still works in WP7 emulators and on my WP7). Regardless of whether the problem is the emulator or not, I want to get a clear understanding of how I should be managing memory in the game. My game consists of a character whom has 4 or more different animations. Each animation consists of 4 to 7 frames. On top of that, the character has up to 8 stackable visualization modifications (eg eye type, nose type, hair type, clothes type). Pre memory issue, I preloaded all textures for each animation frame and customization and created animate action out of them. The game then plays animations using the customizations applied to that current character. I re-looked at this implementation when I received the out of memory exceptions and have started playing with RenderTexture instead, so instead of pre loading all possible textures, it on loads textures needed for the character, renders them onto a single texture, from which the animation is built. This means the animations use 1/8th of the sprites they were before. I thought this would solve my issue, but it hasn't. Here's a snippet of my code: var characterTexture = CCRenderTexture.Create((int)width, (int)height); characterTexture.BeginWithClear(0, 0, 0, 0); // stamp a body onto my texture var bodySprite = MethodToCreateSpecificSprite(); bodySprite.Position = centerPoint; bodySprite.Visit(); bodySprite.Cleanup(); bodySprite = null; // stamp eyes, nose, mouth, clothes, etc... characterTexture.End(); As you can see, I'm calling CleanUp and setting the sprite to null in the hope of releasing the memory, though I don't believe this is the right way, nor does it seem to work... I also tried using SharedTextureCache to load textures before Stamping my texture out, and then clearing the SharedTextureCache with: CCTextureCache.SharedTextureCache.RemoveAllTextures(); But this didn't have an effect either. Any tips on what I'm not doing? I used VS to do a memory profile of the emulation causing the crash. Both WP7.1 and WP8 emulators peak at about 150mb of usage. WP8 crashes and throws an out of memory exception. Each customisation/frame is 15kb at the most. Lets say there are 8 layers of customisation = 120kb but I render then onto one texture which I would assume is only 15kb again. Each animation is 8 frames at the most. That's 15kb for 1 texture, or 960kb for 8 textures of customisation. There are 4 animation sets. That's 60Kb for 4 sets of 1 texture, or 3.75MB for 4 sets of 8 textures of customisation. So even if its storing every layer, its 3.75MB.... no where near the 150mb breaking point my profiler seems to suggest :( WP 7.1 Memory Profile (max 150MB) WP8 Memory Profile (max 150MB and crashes)

    Read the article

  • 2D Array of 2D Arrays (C# / XNA) [on hold]

    - by Lemoncreme
    I want to create a 2D array that contains many other 2D arrays. The problem is I'm not quite sure what I'm doing but this is the initialization code I have: int[,][,] chunk = new int[64, 64][32, 32]; For some reason Visual Studio doesn't like this and says that it's and 'invalid rank specifier'. Also, I'm not sure how to use the nested arrays once I've declared them... Some help and some insight, please?

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >