_id
int64
0
49
text
stringlengths
71
4.19k
12
Add a "fake" Loading Screen I'm working on a 2D game for WPF8 using XNA 4.0. Everything goes great, but it's too fast. I was just wondering, what could I do between the end of the game and the score screen, and before the game starts? I'm looking for a sample of how to do that (black screen with "loading" write in windows phone style) or a way to implement it.
12
How can I support more than one resolution language on WP7 8? I want that my Windows Phone game runs on the following three resolutions 480x800, 768x1280 and 720x1280. And maybe later on 1920x1080. But in the XAP file information, it's just written quot Resolution(s) WVGA quot . What can I support more resolutions than just WVGA? In addition, I want to support more than one language. At the moment, I can just choose English in the Dev Center menu, but I want to support French, Spanish and German too. How can I support French, Spanish and German? I don't know how to add these languages. I uploaded my XAP file in the Dev Center and it gives me the following informations Select a XAP above to view or edit its Store listing and other info. XAP version number 1.0.0.0 XAP details detected from file File name WindowsPhoneGame2.xap File size 167 KB Supported OS 7.1, 8.0 Resolution(s) WVGA Language(s) EnglishNorthAmerica Capabilities ID CAP NETWORKING XAP's Store listing info A XAP file can contain multiple languages. Select a language to add Store listing info specific for that language. English Description for the Store
12
XNA Float values don't work as parameter With the Microsoft XNA Framework I can change the color of a tinted texture by changing it's integer values like so Int x 255 if(true) x tint new Color(x, 255, 255) Draw(texture, Vector2.Zero, tint) If x were a float however the appearance of the sprite wouldn't change until the value x became zero. With integer the texture fades over time with the event change. Why is this? S
12
Why does my sprite animation sometimes runs faster? I don't know why each time I call the Update Animation function, my sprite animation runs faster. Is it caused by gameTime? How to fix it? Here's the relevant code class Character lt SNIP gt public void Update Animation(Point sheetSize, TimeSpan frameInterval, GameTime gameTime) if (nextFrame gt frameInterval) currentFrame.X if (currentFrame.X gt sheetSize.X) currentFrame.X 0 currentFrame.Y if (currentFrame.Y gt sheetSize.Y) currentFrame.Y 0 nextFrame TimeSpan.Zero else nextFrame gameTime.ElapsedGameTime lt SNIP gt private void UpdateMovement(KeyboardState aCurrentKeyboardState, GameTime gameTime) if (mCurrentState State.Walking) action "stand" Update Animation(sheetSize Stand, frameInterval Stand, gameTime) mSpeed Vector2.Zero mDirection Vector2.Zero if (aCurrentKeyboardState.IsKeyDown(Keys.Left) amp amp !aCurrentKeyboardState.IsKeyDown(Keys.Right)) action "run" effect SpriteEffects.None mSpeed.X CHARACTER SPEED mDirection.X MOVE LEFT Update Animation(sheetSize Run, frameInterval Run, gameTime) else if (aCurrentKeyboardState.IsKeyDown(Keys.Right) amp amp !aCurrentKeyboardState.IsKeyDown(Keys.Left)) action "run" effect SpriteEffects.FlipHorizontally mSpeed.X CHARACTER SPEED mDirection.X MOVE RIGHT Update Animation(sheetSize Run, frameInterval Run, gameTime) if (aCurrentKeyboardState.IsKeyDown(Keys.Z) amp amp mPreviousKeyboardState.IsKeyUp(Keys.Z)) mCurrentState State.Hitting if (mCurrentState State.Hitting) action "hit" Update Animation(sheetSize Hit, frameInterval Hit, gameTime) mCurrentState State.Walking lt SNIP gt
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
How many BasicEffects do you have in a Game? What is the best way to render multiple objects shapes at once? I'm trying to understand 3D rendering and it seems that everytime you render a new object (A 3D Cube or something) you need to have a new BasicEffect for each Box you render unless you want the exact same texture? ...so if I have over a hundred boxes with each different textures, I need at least as many BasicEffects? Will that not be "too much" for the CPU GPU in the end or result in lagging? Is there any good way to render multiple objects (cubes or other shapes) at the same time? I've tried changing the BasicEffect.Texture with each cube drawn, but it resulting in changing the first Cube's texture too. Any suggestions would be really appreciated, I'm really new to 3D in XNA so I'm trying to wrap my head around the best methods for example render a Map with objects (of shapes). Example I create some Cube3D (by providing location and size) and it creates a list of Vertices. I have to render it this way gameEffect.TextureEnabled true gameEffect.Texture gameTexture gameEffect.EnableDefaultLighting() foreach (EffectPass pass in gameEffect.CurrentTechnique.Passes) pass.Apply() foreach (Cube3D cube in gameCubes) cube.Render(GraphicsDevice) ...thereby having the same Texture on each Cube. Are there any other ways?
12
How do I make a resolution independent system? I'm blanking on this one. I can anchor stuff on edges of course, that would make my UI resolution independent...until it changes so much that the graphics are too small. How do I scale appropriately whenever needed? How do I keep my graphics at the right proportion while scaling? I don't want them stretched if the resolution has a different proportion like 16 10 as opposed to whatever else. Is there a true and tested approach to this? Video players show black borders because of this problem, is this not properly solvable?
12
XNA Rotation results in a pixelated image I have a "problem" with XNA 4 and spriteBatch. When I draw a rectangle and rotate it, the sides get quite pixelated and look bad example What do I need to do to make the edges look smooth? spriteBatch.Draw(box, new Rectangle(350, 350, 100, 100), null, Color.Red,MathHelper.ToRadians(65), new Vector2(50, 50), SpriteEffects.None, 0.0F) EDIT Found the solution. As Tetrad's comment suggested, one needs to activate anti aliasing. Under XNA4.0 you can use this code GraphicsDeviceManager graphics graphics.PreferMultiSampling true graphics.ApplyChanges()
12
How to implement Ragdoll physics to 2D characters in XNA? I'm starting a new project with XNA. I want to create a game where the main character is subject to ragdoll physics when killed. I was wondering if anyone can give me any tips on how should I implement the character class and apply these ragdoll physics before I start coding so I don't have to refactor my code later. No code is necessary, just a basic overview of an algorithm and some tips. I've found a lot of information about ragdoll physics in 3D but nothig about 2D in XNA.
12
How to loop through objects in class (XNA)? In my game I have an Enemy class, and in that I have a constructor which I use to make Enemy objects. How do I add all Enemy objects to a list or loop through all of them using a foreach loop? I have tried various variations of this foreach(object E in Enemy) Do collision detection, set AIs next move, etc. However, it always rejects the second part of the foreach loop, saying that Enemy is a type but is used as a variable.
12
Why is my cursor not working if I add a scaling matrix? After moving the camera to any direction, my cursor isn't getting drawn on the correct position. For example I move my camera to the right, after that I click on the screen, but the cursor isn't getting drawn on the place I clicked. It's drawn somewhere else on the screen. Why is the cursor not getting drawn on the place I clicked? I need to scale the screen because I want to support different resolutions in a MonoGame project(see my other question) How can I use a camera matrix with different resolutions? I scale like this UPDATE I added the code that I'm using to get the cursor position, and the code that I'm using to draw the cursor. In addition, I use now Matrix.Invert(scaleMatrix camera.GetMatrix())), but it doesn't work. The cursor is still drawn on the wrong position. In my Player class, I get the position of the click(Tap) The Playerposition is the center of the camera public void Update(GameTime gameTime) while (TouchPanel.IsGestureAvailable) GestureSample gs TouchPanel.ReadGesture() switch (gs.GestureType) case GestureType.HorizontalDrag Playerposition new Vector2(gs.Delta.X game1.scaleX, gs.Delta.Y game1.scaleY) break case GestureType.VerticalDrag Playerposition new Vector2(gs.Delta.X game1.scaleX, gs.Delta.Y game1.scaleY) break case GestureType.Tap game1.CursorPosition new Rectangle((int)(gs.Position.X game1.scaleX), (int)(gs.Position.Y game1.scaleY), 10, 10) game1.Clicked true break In Game1 public const int VirtualScreenWidth 800 public const int VirtualScreenHeight 480 public float scaleX, scaleY private Vector3 screenScale protected override void LoadContent() scaleX (float)GraphicsDevice.Viewport.Width (float)VirtualScreenWidth scaleY (float)GraphicsDevice.Viewport.Height (float)VirtualScreenHeight screenScale new Vector3(scaleX, scaleY, 1.0f) protected override void Update(GameTime gameTime) player.Update(gameTime) Updating the camera position Newcameraposition new Vector2(player.Playerposition.X (float)VirtualScreenWidth 2, player.Playerposition.Y (float)VirtualScreenHeight 2) camera.Update(gameTime, Newcameraposition) InvertCursorPos Vector2.Transform(new Vector2(CursorPosition.X, CursorPosition.Y), Matrix.Invert(scaleMatrix camera.GetMatrix())) Calculate the cursor position if (Clicked true) CursorPosition new Rectangle((int)(InvertCursorPos.X Newcameraposition.X), (int)(InvertCursorPos.Y Newcameraposition.Y), 10, 10) Clicked false base.Update(gameTime) Drawing protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.CornflowerBlue) var scaleMatrix Matrix.CreateScale( screenScale) spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.AnisotropicClamp, DepthStencilState.None, RasterizerState.CullNone, null, scaleMatrix camera.GetMatrix()) Drawing the cursor spriteBatch.Draw(CursorSprite, CursorPosition, null, Color.White, 0, Vector2.Zero, SpriteEffects.None, 1) spriteBatch.End()
12
How to import the .fbx scene with multiple objects in XNA so that the objects retain their scene position? I have a scene that contains mutiple objects. How can I import it in XNA and maintain each object position? Right now I export the scene in .fbx and load it in a model like this cube.model contentManager.Load lt Model gt ("cub") But the objects don't retain their position and are all gathered in one point. I need a method to import all the objects as individual objects but to retain the objects position in the scene. (i.e. I need to import the scene so that I may manipulate the objects and retain their position in the scene so that I shouldn't reposition all the objects by myself) The objects are not connected, thus there are no bones. They are individual objects, just placed in some positions. This is my drawing function, the cube is the gameobject. void DrawGameObject(GameObject gameobject) foreach (ModelMesh mesh in gameobject.model.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.EnableDefaultLighting() effect.PreferPerPixelLighting true Matrix b Matrix.Identity effect.World b gameobject.orientation effect.Projection camera.projectionMatrix effect.View camera.viewMatrix mesh.Draw()
12
Why do XNA Monogame models create new BasicEffect instances? My question is fairly straightforward, I think. Using Monogame, when I load a model using contentManager.Load lt Model gt ("Model"), the model's mesh has a BasicEffect attached. That means that if I load multiple models, I'll have multiple BasicEffect instances created, which seems wasteful. Based on other questions I've seen here (and based on instinct), I shouldn't need multiple effects for rendering simple models, but those effects are created by the content pipeline when the model is imported. How do I resolve this problem? Is there a way to tell Monogame to not create effects on load, or do I have to override the effects created by the models manually? Is there something I'm missing in my logic?
12
Drag Gestures fractional delta values I have an issue with objects moving roughly twice as far as expected when dragging them. I am comparing my application to the standard TouchGestureSample sample from MSDN. For some reason in my application gesture samples have fractional positions and deltas. Both are using same Microsoft.Xna.Framework.Input.Touch.dll, v4.0.30319. I am running both apps using standard Windows Phone Emulator. I am setting my break point immediately after this line of code in a simple Update method GestureSample gesture TouchPanel.ReadGesture() Typical values in my app Delta X 13.56522 Y 4.166667 Position X 184.6956 Y 417.7083 Typical values in sample app Delta X 7 Y 16 Position X 497 Y 244 Have anyone seen this issue? Does anyone have any suggestions? Thank you.
12
Why do objects interpenetrate in this simple collision solver? The code below is from a Microsoft XNA sample here. This is quite a simple rigid body simulation that ignores many physical effects (such as angular momentum), but it does try to push objects (spheres) apart so that they are not penetrating one another. However, the simulation allows spheres not only to penetrate, but when many spheres are stacked on top of each other, small spheres can be almost completely inside of larger spheres. If I make all spheres have the same radius and mass, then the simulation performs reasonably well (with minimal interpenetration). Can someone explain why there is any interpenetration at all? Since it moves the positions of the spheres, it seems like interpenetration should be impossible. For each sphere in the simulation, this method is called on every other sphere. lt summary gt Given 2 spheres with velocity, mass and size, evaluate whether a collision occured, and if so, excatly where, and move sphere 2 at the contact point with sphere 1, and generate new velocities. lt summary gt private void SphereCollisionImplicit(Sphere sphere1, Sphere sphere2) const float K ELASTIC 0.75f Vector3 relativepos sphere2.Position sphere1.Position float distance relativepos.Length() float radii sphere1.Radius sphere2.Radius if (distance gt radii) return No collision Add epsilon to avoid NaN. distance 0.000001f Vector3 relativeUnit relativepos (1.0f distance) Vector3 penetration relativeUnit (radii distance) Adjust the spheres' relative positions float mass1 sphere1.Mass float mass2 sphere2.Mass float m inv 1.0f (mass1 mass2) float weight1 mass1 m inv relative weight of sphere 1 float weight2 mass2 m inv relative weight of sphere 2. w1 w2 1.0 sphere1.Position weight2 penetration sphere2.Position weight1 penetration Adjust the objects relative velocities, if they are moving toward each other. Note that we're assuming no friction, or equivalently, no angular momentum. velocityTotal velocity of v2 in v1 stationary ref. frame get reference frame of common center of mass Vector3 velocity1 sphere1.Velocity Vector3 velocity2 sphere2.Velocity Vector3 velocityTotal velocity1 weight1 velocity2 weight2 Vector3 i2 (velocity2 velocityTotal) mass2 if (Vector3.Dot(i2, relativeUnit) lt 0) i1 i2 0, approx Vector3 di Vector3.Dot(i2, relativeUnit) relativeUnit i2 di (K ELASTIC 1) sphere1.Velocity ( i2) mass1 velocityTotal sphere2.Velocity i2 mass2 velocityTotal In particular, I though that this sphere1.Position weight2 penetration sphere2.Position weight1 penetration Should completely disallow any interpenetration, why doesn't it?
12
Loading custom shader in Monogame I have been trying to load this custom FX file into a Monogame project, and everything I try fails. (code taken from http www.david gouveia.com scrolling textures with zoom and rotation ) sampler TextureSampler register(s0) float2 ViewportSize float4x4 ScrollMatrix void SpriteVertexShader(inout float4 color COLOR0, inout float2 texCoord TEXCOORD0, inout float4 position POSITION0) position.xy 0.5 position.xy position.xy ViewportSize position.xy float2(2, 2) position.xy float2(1, 1) texCoord mul(float4(texCoord.xy, 0, 1), ScrollMatrix).xy technique SpriteBatch pass VertexShader compile vs 2 0 SpriteVertexShader() If I convert it to an XNB file, and attempt to load it via the Content processor, it says "Could not load asset!", indicating that the file cannot be found. The XNB file is there along with the rest of the content, it is just not being loaded. Next, I compiled the FX files into a MGFX file using 2MGFX. I included the MGFX files as an embedded resource and attempted to load the file by doing Effect test new Effect(GraphicsDevice, Properties.Resources.parallax) This crashed at Effect.cs saying argument out of range error. What do I need to do to use this shader in Monogame?
12
XNA Render Targets Depth Testing I imagine this is a problem that gets asked quite often, but reading up on it I can't seem to get a definitive answer on how to solve it. I've got two HLSL shaders (I've simplified them in the example to just output a colour) that require RenderTargets. For example Blur shaders. There are two balls spinning around a central point. As they spin, one passes between the other and the camera occluding the other ball and vice versa. If I render them both to the same rendertarget (using the same technique) they obviously share a depth buffer, and the depth testing happens correctly. However, when I need to use different techniques to render each ball seperately (one ball to one rendertarget and the other ball to a different) and then try to composite them depth testing fails and they are just rendered on top of each other. Attach is the code I'm using. I've simplified it down a lot, but it indicates the problem I'm having. How do I go about rendering two different objects, using two different techniques to two different rendertargets and then composite them? DepthTesting.cs effect.fx
12
How do I use a PC Dance Pad with Xna? I have a Dance Pad and I want use it in XNA as a controller. It has a USB connection. Can someone help me?
12
Setting up 3d Collision for Primitive shapes Im having some trouble understanding how to set up collision detection between my first person camera and my primitive shapes which are made using the vertex buffer. Do i give my camera a boundingBox and all my objects a boundingbox then add them to a list and check the list for collsions or is there a better more understanding way to do this. My game is literally a maze game so all i really need is my camera to accept collisions against the primitive objects. Thanks in advance.
12
Using sourceRect or cropping out a Texture 2D to draw? MonoGame XNA I was wondering what is the best way to draw textures (for performance). Using the sourceRectange in the spriteBatch.Draw() call and just draw the whole spriteSheet, or crop out every texture on the spritesheet and store them in there own Texture2D object? Like this public static Texture2D Crop(Texture2D spriteSheet, Rectangle source) Texture2D croppedTexture2d new Texture2D(spriteSheet.GraphicsDevice, source.Width, source.Height) Color imageData new Color spriteSheet.Width spriteSheet.Height Color croppedImageData new Color source.Width source.Height spriteSheet.GetData lt Color gt (imageData) int index 0 for (int y source.Y y lt source.Y source.Height y ) for (int x source.X x lt source.X source.Width x ) croppedImageData index imageData y spriteSheet.Width x index croppedTexture2d.SetData lt Color gt (croppedImageData) return croppedTexture2d And just call that method in the LoadContent() method?
12
Billboards offset for character names rotation I am successfully using Matrix.CreateBillboard in my XNA game to print the characters name above the models. The problem I have is with the offset (to appear above the models). Currently, I am creating the location of the text using Vector3 objTextPosition objPlayerShip.objShipVector new Vector3(0, 3, 0) This works fine if I stay within the same general lateral location. If I rotate above or below the model the text either appears on top of, or is covered by (or even below) the model. To compensate for this, I would need to create a rotation around the model (should I use a quaternion?) with the top always pointing up (with a Vector3(0, 3, 0) offset). Am I over thinking this? Is there a simple way to achieve this? Thanks in advance! Here is the correct way (above the model) Here is looking from top, down
12
How to access SpriteBatch, Input, and ContentManager from all game screens? I'm trying to make a Game State Manager and I'm using the Microsoft Game State Management Sample as guidance. However, I want a more simplistic design (no transitions, reflection, or support for 360 Phone). Now, I am diverging a bit in to my own design. I figure every single game screen is going to need access to the SpriteBatch, ContentManager, and Input. Input is a class I defined to detect key and mouse presses releases etc. Currently I'm just using regular old dependency injection and just passing those three references in to the constructor of all newly created screens, but the code repetition is bugging me slightly. Since all screens in my game are going to need to detect input, load content, and draw to the screen, I'd prefer a solution where I wouldn't have to cumbersomely pass and include these three objects in all new game screens. However, I'm not sure how exactly to do this. I suppose the Game Screen Manager could maintain a reference to all of these objects, but then each game screen would have to maintain a reference to the game screen manager, which just sounds wrong. Also, they would have to be public properties on the game screen manager and I'm not sure I want to expose that much information to potential clients. Ideally, each game screen would not have to know about the game screen manager and would somehow have access to these three essential objects without requiring them in all of their constructors. Any ideas? Thanks.
12
Problem with Update(GameTime) Methods and Pause implementation I have the pause function implemented and it works correctly in that it dims the player screen and stops updating the gameplay. The problem is that GameTime continues to increase while it is paused, so my method that checks gameTime versus previousSpawnTime before spawning another enemy gets messed up and if the game is paused too long it is noticeable that the next enemy draws far too early. Here is my code for the enemy update. private void UpdateEnemies(GameTime gameTime) Spawn a new enemy every 1.5 seconds if (gameTime.TotalGameTime previousSpawnTime gt enemySpawnTime) previousSpawnTime gameTime.TotalGameTime Add an Enemy AddEnemy() ... I also have other methods that depend on gameTime. I've tried getting the total pause time and subtracting that from the total game time, but I can't seem to get it to work correctly if that is the way I should go about solving this. If you need to see any other code let me know. Thank you.
12
How do I check collision when firing bullet? I'm currently creating 2D game from top perspective. I'm having problems with bullets. Yes, I currently simulate their movement so user can see them (about 2x ). Moving them with this is static Direction new Vector2(mouse.X, mouse.Y) new Vector2(player.x, player.y) Direction.Normalize() Speed 900f this is called in Draw(GameTime gameTime) Position Direction 9f Speed (float)gameTime.ElapsedGameTime.TotalSeconds actually it's working perfectly, however, they're too fast so I can't check their collision each frame and I need to re play their way each frame. How would I do it? And how would I do this available for both server (which doesn't use XNA as I want to port it to Linux later) and client (using XNA)? Here's an image which shows the problem (1. bullet is before target 2. bullet is behind target, so it can no longer intersect the target. My goal is to calculate whether it intersected the target before) I have almost forgot to mention! These objects are moving, these are player, that means that user can get out of the bullet's trace
12
2d shapes in XNA 4.0? Having some experience of XNA but none of 3D programming. I have an idea i want to realize but i have not decided to do it in 3d or 2d. Im not sure which one will be best in XNA. I want to have a shape like a blob that can reshape depending on input. The morphing does not need to be very advanced. It could be a circle (2d) or globe (3d) that just has one point that moves slightly in a random direction. In ASP.NET i have made this through the 2d Draw classes where i can make lines, circles, squares etc and then modify the points that makes them up. But it seems to me that XNA does not have classes for making 2d shapes (can i get this confirmed?). If it had, then this would be the quickest solution for me.
12
In XNA, should I use the built in game component classes? I'm just getting started on an XNA game for Window Phone 7. For my Flash games I have my own framework that I was just going to port from AS3, but I have just found the built in game component stuff in XNA. So should I use this stuff? Should my Entity class extend game component drawable game component? I'm sure it will be quicker just to port my AS3 code, but I thought this built in stuff may have some advantages? UPDATE I decided not to use them. It doesn't seem that they are meant to be used in the way I described.
12
What are the practical limitations of using XNA? Since development on XNA has long since stopped, it is unlikely that it will ever be updated to be in line with modern graphics technology, however aside from the obvious fact that it's Windows only what are the practical limitations of using XNA? The obvious ones are It uses DirectX 9.0 which means no compute or geometry shaders. It's Windows only (Excluding Monogame FNA) It requires the installation of .NET and XNA on a client's computer. 2 and 3 are obvious limitations, but can be considered acceptable. 1 on the other hand, is a bit more complicated. In practical terms what does being limited to DirectX 9.0 mean in terms of game development and graphical capability? No geometry or compute shaders means having to do more heavy lifting on the CPU, but is there any other limitations that an end user would notice? Ideally beyond a generic term such as "graphical fidelity".
12
Scaling Rotating triangle I have a Triangle class and a list of triangles representing my 3D model shape. When I update the position, the rotation or the scale of my model, I also want my triangles list to be updated. I already made the function to update triangle position, but I can't make it for rotation scale... private void UpdateModelTrianglesPos(Vector3 oldPos, Vector3 newPos) Vector3 diff newPos oldPos for (int i 0 i lt trianglesPositions.Count i ) trianglesPositions i .UpdatePosition(diff) Thank you for your help!
12
8 directional movement Maintain vertical position I have a top down game that has 8 directions of movement (top down left right topright topleft bottomright bottomleft). There are sprites for each direction of movement. This is just an example spritesheet The problem is when I want to retain the vertical position. When I let go of the buttons on the keyboard, it polls the keys quickly and ends up facing the character in either left right up down position depending on the last key that was released. I added a delay for polling the keypresses, but I do not like this solution as it creates a noticeable lag. Can anyone think of logic that would be able to allow my sprite to retain the proper direction when the keys are unpressed? Here is the current code if (kbState.IsKeyDown(Keys.Up) amp amp kbState.IsKeyDown(Keys.Left)) character.ChangeDirection(Direction.UpLeft) else if (kbState.IsKeyDown(Keys.Up) amp amp kbState.IsKeyDown(Keys.Right)) character.ChangeDirection(Direction.UpRight) else if (kbState.IsKeyDown(Keys.Down) amp amp kbState.IsKeyDown(Keys.Left)) character.ChangeDirection(Direction.DownLeft) else if (kbState.IsKeyDown(Keys.Down) amp amp kbState.IsKeyDown(Keys.Right)) character.ChangeDirection(Direction.DownRight) else if (kbState.IsKeyDown(Keys.Up)) character.ChangeDirection(Direction.Up) else if (kbState.IsKeyDown(Keys.Down)) character.ChangeDirection(Direction.Down) else if (kbState.IsKeyDown(Keys.Left)) character.ChangeDirection(Direction.Left) else if (kbState.IsKeyDown(Keys.Right)) character.ChangeDirection(Direction.Right) Edit Settled for the following code float delay 0.04f float DELAY 0.04f .... Get movement delay (float)gameTime.ElapsedGameTime.TotalSeconds if (delay lt 0) int vertical kbState.IsKeyDown(Keys.Up) ? 1 kbState.IsKeyDown(Keys.Down) ? 1 0 int horizontal kbState.IsKeyDown(Keys.Left) ? 1 kbState.IsKeyDown(Keys.Right) ? 1 0 movement new Vector2(horizontal, vertical) delay DELAY character.Update(gameTime, movement) Seems I have to use a delay in order to get this to work. Thanks for the feedback guys.
12
Create a car sound with frequencies Im trying to create a car game in c sharp! Im now trying to figure out a way to get some sounds into the game! For example, the acceleration sound of the car. I recently tried to add a 5 second sound of a real car accelerating, but I don't think its the right way to do it. Because then i have to start from the beginning all the time of the clip when i accelerate. Is there maybe some way to work with frequencies? To send a frequency to the speakers and then just increase it when I accelerate (And to make it sound like a car) I've heard about PWM, could that be something? Thanks!
12
write to depth buffer while using multiple render targets Presently my engine is set up to use deferred shading. My pixel shader output struct is as follows struct GBuffer float4 Depth DEPTH0 depth render target float4 Normal COLOR0 normal render target float4 Diffuse COLOR1 diffuse render target float4 Specular COLOR2 specular render target This works fine for flat surfaces, but I'm trying to implement relief mapping which requires me to manually write to the depth buffer to get correct silhouettes. MSDN suggests doing what I'm already doing to output to my depth render target however, this has no impact on z culling. I think it might be because XNA uses a different depth buffer for every RenderTarget2D. How can I address these depth buffers from the pixel shader?
12
Simple Update loop to show questions one at a time I have two lists which work with an XML file which holds questions and answers. At the moment the project displays all the questions at the same time so they "flicker" on the screen and iterate between each item in the list. Whats the easiest way (coding) to pause the random generated list on any particular questions? Question class class question public string questionString public string apple public string pear public string orange the ? indicate the int can be nullable so it can accept the string item int? correctAnswer public question(string newquestionString) parseQuestion(newquestionString) public void parseQuestion(string newquestionString) List lt string gt questionComponents newquestionString.Split(' ').ToList lt string gt () questionString questionComponents 0 apple questionComponents 1 pear questionComponents 2 orange questionComponents 3 correctAnswer Int32.Parse(questionComponents 4 ) In Game1 Random q new Random() int i q.Next(questions.Count) spriteBatch.Begin() spriteBatch.DrawString(myfont, questions i , new Vector2(100 100 i, 100), Color.Black) spriteBatch.DrawString(myfont, myQuestions i .questionString, new Vector2(100 100, 100), Color.Black) spriteBatch.DrawString(myfont, myQuestions i .apple, new Vector2(100 100, 200), Color.Black) spriteBatch.DrawString(myfont, myQuestions i .orange, new Vector2(100 100, 300), Color.Black) spriteBatch.DrawString(myfont, myQuestions i .pear, new Vector2(100 100, 400), Color.Black) spriteBatch.End()
12
Position is not what it should be when attaching fixture In XNA Farseer I have something like this Body body BodyFactory.CreateRectangle(world, 1f, 2f, 1f) FixtureFactory.AttachCircle(0.5f, 1f, body, new Vector2(0f, 1f)) I have been told that body.Position property is the center of the AABB of the Body. In this example it seems not to be so. When I do something like this to display the coordinates of the position I see that they are at the center of the rectangle created at the beginning BodyFactory.CreateCircle(world, 0.1f, 1f, Body.Position) BodyFactory.CreateCircle(world, 0.1f, 1f, Body.WorldCenter) The center of gravity seems also to be the same. I need this for drawing my texture over the Body. The origin for drawing is then like this Vector2 Origin new Vector2(Sprite.Width 2, Sprite.Height 2) Am I doing something wrong or does the engine not recognize, that a circle fixture is attached to the rectangle? Is there any workaround?
12
Custom VertexDeclaration for Color, Texture, Normal What is the best way to create a VertexDeclaration, that makes it able to render a Shape consisting of vertices and also be able to store a color for the shape (in case the texture can't be rendered or in case we want color instead of a texture) instead of having both a VertexPositionNormalTexture and a VertexPositionColor struct in the same class struct. I'm trying this approach public interface IShape IVertexType public struct ShapeFace public int Count get set public Color Color get set public Vector3 Position get set public Vector2 TextureCoordinates get set public Vector3 Normal get set public Vector3 Vertices get set Perhaps I need this? public int Indexs get set public struct Shape IShape public ShapeFace Faces get set Need to implement VertexDeclaration here How do I implement the VertexDeclaration to understand what I want to do? A shape contains faces, each face can have it's own texture OR color, normal mapping, texture coordinates, etc. Example A cube has 6 faces, each face needs 2 triangles, each triangle has 3 points. 6 2 3 36 vertices. This way I can create a cube with 6 faces instead of 36 vertices, and render it in color or with a texture. I really want to simplify it so that I can create some kind of struct that works this way.
12
XNA 3rd Person Camera pitch reverses when facing backwards? I have a 3rd person camera which rotates around the Y axis fine (yaw) and when I am facing forward (0, 0, 1) moving the mouse up moves the camera up and down great. But the more I turn the player and camera the the less the camera moves up and down until I get to 90 degrees where it almost stay still and at 180 it moving the mouse up moves the camera down! Any ideas? How should I be calculating camera pitch? The player only yaws it does not roll or pitch. The camera yaws and pitches. The cameras update method looks like public void Update(Vector3 playerPos, float pitch, float yaw) Matrix rotation Matrix.CreateRotationY(yaw) Matrix.CreateRotationX(pitch) Vector3 newOffset Vector3.Transform(offsetAmount, rotation) cameraPos playerPos newOffset View Matrix.CreateLookAt(cameraPos, playerPos, Vector3.Up) Projection Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, Constants.AspectRatio, Constants.NearClip, Constants.FarClip)
12
How to determine depth of a pixel perfect collision I am trying to figure out how to determine the depth of a pixel perfect collision in XNA. I want to know the depth in order to be able to use it in my collision response. At the moment I have the following code, that provides me with a working pixel perfect collision detection public static bool IntersectPixels(Matrix transformA, int widthA, int heightA, Color dataA, Matrix transformB, int widthB, int heightB, Color dataB) Matrix transformAToB transformA Matrix.Invert(transformB) Vector2 stepX Vector2.TransformNormal(Vector2.UnitX, transformAToB) Vector2 stepY Vector2.TransformNormal(Vector2.UnitY, transformAToB) Calculate the top left corner of A in B's local space This variable will be reused to keep track of the start of each row Vector2 yPosInB Vector2.Transform(Vector2.Zero, transformAToB) For each row of pixels in A for (int yA 0 yA lt heightA yA ) Start at the beginning of the row Vector2 posInB yPosInB For each pixel in this row for (int xA 0 xA lt widthA xA ) Round to the nearest pixel int xB (int)Math.Round(posInB.X) int yB (int)Math.Round(posInB.Y) If the pixel lies within the bounds of B if (0 lt xB amp amp xB lt widthB amp amp 0 lt yB amp amp yB lt heightB) Get the colors of the overlapping pixels Color colorA dataA xA yA widthA Color colorB dataB xB yB widthB If both pixels are not completely transparent, if (colorA.A ! 0 amp amp colorB.A ! 0) then an intersection has been found return true Move to the next pixel in the row posInB stepX Move to the next row yPosInB stepY No intersection found return false How would I determine how deep the collision is into the dataB texture data?
12
Tons of stuttering in XNA? As stated in the title, my program stutters like crazy, even though my program for the most part runs for 60 fps. During the moments it stutters, FPS momentarily drops down to 59(stats from FRAPS). Here is an video capture of the stuttering in action. If you look closely, you can see the game stutter around 3 4 times. It is much more noticeable in real life. http gfycat.com SevereCanineBabirusa CLR Profiler shows that garbage collection doesn't run at all during that time, never mind 4 times, so it's not that. Here's the code for movement Movement logic Increase the speed speed Math.Min(speed (speedIncrement (gameTime.ElapsedGameTime.Milliseconds 200.0f)), maxSpeed) for (int i fruits.Count 1 i gt 0 i ) Move the fruits fruits i .pos.Y speed gameTime.ElapsedGameTime.Milliseconds fruits i .rect.Y (int)fruits i .pos.Y Check if the fruit is past the screen. If it is, remove it from fruits if (fruits i .rect.Y gt screenHeight) fruits.Remove(fruits i ) IsFixedTimeStep is set to false, but SyncronizeWithVerticalTrace is on. Any idea what could be the cause of the stuttering? EDIT Apparently it was a combination of this http answers.microsoft.com en us windows forum windows 7 performance presentationfontcacheexe uses 50 of my cpu 4200fe85 458f 4f19 b791 1fe5395304da and f.lux eating up my CPU GPU cycles.
12
How can I use XNA with Visual Studio Express 2013 for Windows? http dev.windowsphone.com en us downloadsdk I downloaded the current version of Visual Studio to develop Windows Phone apps, but I don't know how to add XNA. I tried to install XNA, but it's not working with Visual Studio. How can I use XNA with Visual Studio Express 2013 for Windows?
12
What is the best way to code the XNA gameserver for an FPS game? I'm writing an FPS XNA game. It is going to be multiplayer, so I came up with the following I'm making two different assemblies one for the game logic, and one for drawing it and the game irrelevant stuff (like rocket trails). The type of the connection is client server (not peer to peer), so every client connects to the server, and then the game begins. I have decided to use the XNA.Framework.Game class, for the clients to run their game in window (or fullscreen), and the GameComponent DrawableGameComponent classes, to store the game objects, update, and draw them on each frame. What should I do on the server side? I got few options Create my own Game class on the server, which will process all the game logic, without graphics. I am not using the standard Game class because, when I call Game.Run(), the white window appears and I cant figure out how to get rid of it. Somehow, use the original XNA Game class, which already has the GameComponent collection and Update event (60 times per second, just what I need). I have additional questions First, what socket mode should I use? TCP or UDP? How do I actually let the client know the order in which packets are meant to be processed? Second, if I am going to use the exact GameComponent class for the game objects, which are stored and processed on the server, how do I get them to draw on the client side? Should I inherit them, while they are combined in an assembly), or something else?
12
Isometric drawing "Not Tile Stuff" on isometric map? So I got my isometric renderer working, it can draw diamond or jagged maps...Then I want to move on...How do I draw characters objects on it in a optimal way? What Im doing now, as one can imagine, is traversing my grid(map) and drawing the tiles in a order so alpha blending works correctly. So, anything I draw in this map must be drawed at the same time the map is being drawn, with sucks a lot, screws your very modular map drawer, because now everything on the game (but the HUD) must be included on the drawer.. I was thinking whats the best approach to do this, comparing the position of all objects(not tile stuff) on the grid against the current tile being draw seems stupid, would it be better to add an id ON the grid(map)? this also seems terrible, because objects can move freely, not per tile steps (it can occupies 2 tiles if its between them, etc.) Dont know if matters, but my grid is 3D, so its not a plane with objects poping out, its a bunch of pilled cubes.
12
XNA 2D Tile Map zooming to arbitrary point I'm working on a game in XNA with a 2D tilemap as the playfield. I'm using a spritebatch with a transformation matrix to provide movement and scaling of the playfield. I'm trying to add a zoom function, so the player can click anywhere on the screen and it will zoom in to that point. The issue is that when I increase or decrease the scale, the "focus" of the zoom is always at the top left hand corner of the screen. So unzoomed And when zoomed in (note the position of the chequered tile) What I'd like to happen when the player zooms is that it zooms into the centre of the screen, like so (I achieved this by moving the playfield around after zooming) I realise that the way to do this is probably to add or subtract from the X Y co ordinates that get fed into the transformation matrix, and probably at a fraction of the scale, but I can't figure this out. Everything I try tends to result in crazy effects while zooming. Ideally I'd like to be able to set any arbitrary point on the screen, and zoom to that point. Can you help? The code of the Draw function protected override void Draw(GameTime gameTime) Matrix transformMatrix Matrix.CreateTranslation( baseX, baseY, 0) Matrix.CreateScale(baseR, baseR, 1) GraphicsDevice.Clear(Color.CornflowerBlue) "World" spritebatch. Scaling applied. spriteBatch.Begin(SpriteSortMode.FrontToBack, null, SamplerState.PointClamp, null, null, null, transformMatrix) foreach (Vector3 Square in Squares) spriteBatch.Draw(Textures (int)Square.Z , new Vector2(Square.X, Square.Y), null, Color.White, 0, new Vector2(0, 0), 1, SpriteEffects.None, 0.82f) base.Draw(gameTime) spriteBatch.End() "UI" spritebatch. No scaling applied. spriteBatch.Begin(SpriteSortMode.FrontToBack, null, SamplerState.PointClamp, null, null) spriteBatch.Draw(Textures 0 , new Vector2(ScreenMidX, ScreenMidY), null, Color.White, 0, new Vector2(0, 0), 1, SpriteEffects.None, 1f) SpriteFont aFnt Content.Load lt SpriteFont gt ("Font1") spriteBatch.DrawString(aFnt, "" baseX, new Vector2(5, 0), Color.White, 0f, Vector2.Zero, 1f, SpriteEffects.None, 1f) spriteBatch.DrawString(aFnt, "" baseY, new Vector2(100, 0), Color.White, 0f, Vector2.Zero, 1f, SpriteEffects.None, 1f) spriteBatch.End() Full code available here https www.dropbox.com s zft5b20st8o7jv7 ZoomTest3.zip Thanks for any help!
12
MonoGame not all letters being drawn with DrawString I'm currently making a dynamic user interface for my game and are setting up having text on my buttons. I'm having an odd issue where, when i use a specific piece of code to determine the text position, it will not render all of the text passed to DrawString. Even weirder, is if i insert another DrawString after this, drawing more text at a different place, different parts of the text will be drawn. The code for drawing my button with the text attached is public override void Draw(SpriteBatch sb, GameTime gt) sb.Draw(currentImage, GetRelativeRectangle(), Color.White) sb.DrawString(font, text, new Vector2(this.GetRelativeDrawOffset().X this.Width 2 font.MeasureString(text).X 2, this.GetRelativeDrawOffset().Y this.Height 2 font.MeasureString(text).Y 2), textColor) The methods in the creation of the Vector2 simply get the draw position of the button. I'm then doing some calculation to center the text. This produces this when the text is set to 'Test' And when i enter this piece of code below the first DrawString sb.DrawString(font, "test", new Vector2(500, 50), Color.Pink) I should mention that that grey square is being drawn in the same spritebatch, before the button and the text. Any ideas as to what could be causing this? I have a feeling it may be due to draw order, but i have no idea how to control that.
12
Shadows moving with camera. I'm using MJP's Cascade Shadow Map code and I'm having major issues with the shadows moving with the camera. Here a video to demonstrate what's going on. Also, is there a way to fix the dueling frustum issue? It's annoying seeing them pop in and out of corners of the screen. Video of the shadows c and shader code
12
How can I use a camera matrix with different resolutions? I created a little jump'n'run game. The character(Mario) is always the center of the viewport. The game is running correctly if I use the resolution 800x480 pixel. But when I use another resolution(for example 1280x768), the sprites in the viewport look completely different to the sprites in the 800x480 viewport. I want that the viewport(and the sprites in the viewport) looks always the same, on every single resolution. How can I do that? Should I change something on my camera matrix parameters or what should I change so that the viewport and the proportions of the sprites look always the same? I use Monogame to run the game on different Windows Phone devices. My camera class public class Camera public Vector2 Cameraposition public Camera(Vector2 cameraposition) Cameraposition cameraposition public void Update(GameTime gameTime, Vector2 CamPosition) Cameraposition CamPosition public Matrix GetMatrix() return new Matrix(1, 0, 0, 0, 0, 1, 0, 0, Cameraposition.X, Cameraposition.Y, 1, 0, Cameraposition.X, Cameraposition.Y, 0, 1) In Game1 I use the camera in Game1 like this At the beginning(in LoadContent) Vector2 cameraposition new Vector2(PlayerStartpos.X GraphicsDevice.Viewport.Width 2, PlayerStartpos.Y GraphicsDevice.Viewport.Height 2) camera new Camera(cameraposition) Updating the camera position protected override void Update(GameTime gameTime) player.Update(gameTime) Newcameraposition new Vector2(player.Playerposition.X GraphicsDevice.Viewport.Width 2, player.Playerposition.Y GraphicsDevice.Viewport.Height 2) camera.Update(gameTime, Newcameraposition) base.Update(gameTime) Drawing spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.AnisotropicClamp, DepthStencilState.None, RasterizerState.CullNone, null, camera.GetMatrix()) ...
12
Should I take line thickness into consideration for a grid based light game? I'm currently rewriting some horrific code I wrote for a prototype and have stumbled right at the start! The game I'm working on revolves around directing light and there is a small ambiguity in regards to the way the grid is drawn Code wise, information about each node of the grid is stored in an int , , the grid lines are drawn for debugging purposes. Currently there is nothing explicitly defined for the line thickness, i.e if you look at the pixels closely, the bottom and right lines are drawn in a way which means the grid is not centered on screen, it is one pixel out! If you shrink the scale of the grid to each being cell being 4x4 pixels the problem is really obvious The red area is the cell the lines show how I draw the grid lines and what the light beams travels across. Would it better to represent this as a grid of 3x3 pixel cells with a line thickness of 1? Normally I wouldn't be bothered too much because this is really looking into it in a lot of depth, but since the lines of light themselves actually traverse these currently non existing lines I thought it might be better to make the representation a more elegant! What do you think?
12
XNA When to call LoadContent I have an enum in my game that denotes the game state ie MainMenu, InGame, GameOver, Exit and I was wondering if it would be advisable to add a new one in for PrepGame in which the game creates viewports for however many players there are, creates the battlefield etc. I feel like this is a good idea except for one thing should I make a call back to LoadContent() in this state? I could just put a switch statement in the LoadContent for my currentGameState. If it equals PrepGame load things like the skybox, ship models, texures, HUD graphics etc. Or is it a good idea to create an Asset Manager class in the first call to LoadContent() and load everything then. I feel like both approaches have different benefits faster, but more load times vs slower initial load time, but then all my objects are referencing the same variables so I only have to load each on once. Any help is greatly appreciated. Thanks, Peter
12
How can I achieve a pseudo 3D camera effect like this? I am trying to achieve a pseudo 3D camera effect similar to this I have gotten the following results using a 3D camera and billboards I am now running into the following problems In the first billboard example, the size discrepancy between when the sprites are at the "front" and "back" is too great. I need to have them be more similar to the above. The bottom y coordinate of the sprites never seem to change in my example, but they do (slightly) in the example that I want. I need to be able to control how close to the right and left edge of the screen the sprites go to. In the first billboard example I setup my camera like so (float fovxDegrees, float aspect, float znear, float zfar) this.simpleCamera.Perspective(75f, 1.5f, 0.01f, 400) (Vector3 eye, Vector3 target, Vector3 up) this.simpleCamera.LookAt(new Vector3(0, 5f, 10f), Vector3.Zero, Vector3.Up) My sprites are positioned at the following locations new Vector3( 4f, 1f, 0f) new Vector3( 4f, 1f, 1f) Full CSharp code http pastebin.com 9G0FDNLs Billboard HLSL http pastebin.com uB8e3gXU If you want the grid http pastebin.com R5UCBNWt
12
XNA weird effect by matrixTransform of spriteBatch on isometric tile I wrote a Camera class that contains Matrix (for zooming and moving around). When I zoomed it with any zoom scale other than 1, some isometric grids becomes visible on each of my isometric tile. Camera.cs Producing the matrix from previously set Zoom and Location public static void Update() Transform Matrix.CreateTranslation(Location.X, Location.Y, 0) Matrix.CreateScale(Zoom,Zoom,1) InverseTransform Matrix.Invert(Transform) Game.cs spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, null, Camera.InverseTransform) Some Drawing spriteBatch.End() PS Actually, I really want these grids to be visible for zoom scale of 1.0f too. Having these grids make my game looks more like a tile based game. Before Zoom (Scale 1.0f) After Zoom (Zooming in) After Zoom (Zooming out) Zooming very close (Grid line appears to be more than one pixels)
12
What is the most efficient way to work with lip sync facial expressions in XNA? I've been searching for an answer forever, but I haven't found one. What options are there for lip sync facial expressions in video games made with XNA? I have a few models for a game I'm building, and I would like to know if it would be better to set up an animation for every dialogue, but that would be very time consuming and the whole collection of files would result in a massive sized program. I was thinking about an automated lip sync system, but I wouldn't know where to start! Any thoughts?
12
Converting a Flash animation to Silverlight I recently had an animated logo done in Flash for Deen Games. I need to display in all my Silverlight games. The problem is, the logo is about 8 seconds long (205 frames) if I export all the images as even JPEGs, the result is almost 3.5MB of content (more than the game itself). I tried exporting as various formats (PNG, JPG, GIF, etc.) but nothing is small enough. What are my options? How can I incorporate these into my game without blowing up the file size? There's always the option of "recreate it in game with animation rotation etc. as it is now) but that's tons of work and I'd rather avoid that. And no, just a static image is not good enough! Edit Exporting as a movie (AVI, MPEG) won't work since XNA doesn't support movies at this time.
12
In XNA, how do I access a model's dimensions with code? I'm trying to rotate a model around some axes, but this rotates it around the world origin. I understand that I need to translate the object relative to its own size before rotating it, but I don't know by how much. I've done it by trial and error until now. How can I automatically read a model's width, height and position?
12
How can I implement screen transitions like in the 2D Zelda games? I want to implement a screen transition in the style of the 2D Legend of Zelda games (like this). That is, I'd the screen to remain static until the player moves to an exit, at which point the next screen smoothly scrolls into view as the old screen scrolls out of view. How can I accomplish this?
12
How to implement simple shadows on XNA? UPDATE See photos below the description I try desperately to implement shadows on my XNA games. My game is a style of games like Voxel (minecraft). The problem is that I do not find support help or example explaining how to add shadows on cubes (vertices and indices) with (BasicEffect). I just find examples to add shadows with a (HLSL Effect) or a "Model". Is it possible to create shadows with the class "BasicEffect" on vertices cube ? I already try with "Matrix.CreateShadow(...)" but no success . I really hope so. The logic of my function "DrawWorld" region DrawWorld Draw all cubes in the world public void DrawWorld(GameTime gameTime) effet.TextureEnabled true Plane lightPlane new Plane(Vector3.UnitY, 0) Vector3 lightPos new Vector3( 10f, 10f, 10f) Try to initialize shadowMatrix Matrix shadowMatrix Matrix.CreateShadow(Vector3.Normalize(lightPos), lightPlane) Light settings effet.LightingEnabled true effet.DirectionalLight0.Enabled true effet.DirectionalLight1.Enabled true effet.DirectionalLight2.Enabled true effet.DirectionalLight0.DiffuseColor col.ToVector3() effet.SpecularPower 512f Fog settings effet.FogEnabled true effet.FogStart arcadia.camera.NearPlane effet.FogEnd arcadia.camera.FarPlane effet.FogColor Microsoft.Xna.Framework.Color.White.ToVector3() Set World with shadow matrice effet.World Matrix.Identity shadowMatrix effet.View arcadia.camera.View effet.Projection arcadia.camera.Projection Set the cube vertexBuffer and indice arcadia.Game.GraphicsDevice.SetVertexBuffer(graphicData regionIndex a .VertexBuffer) arcadia.Game.GraphicsDevice.Indices graphicData regionIndex a .IndexBuffer Apply the basic effect effet.CurrentTechnique.Passes 0 .Apply() Draw the cubes vertices arcadia.Game.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, graphicData regionIndex a .VertexPosition.Length, 0, graphicData regionIndex a .Indices.Length 3) END OF DRAWWORLD endregion Without shadow is this When i try to add shadow with "Matrix.CreateShadow(...)" i got this bad result
12
Create BoundingBoxes on a Model I am trying to create multiple BoundingBoxes on a Model by following this tutorial https electronicmeteor.wordpress.com 2011 10 25 bounding boxes for your model meshes However, I keep getting this error Requested range extends past the end of the array. on this line part.VertexBuffer.GetData(part.VertexOffset stride, vertexData, 0, part.NumVertices, stride) I can't figure out why it is giving me that. I load my model and try to create the boxes like this Model model this.Content.Load lt Model gt ("Cube") MeshModel box new MeshModel(model) Instead of passing a String path of the model, I just pass the Model itself (I changed the constructor to accept Model model). Any help would be appreciated! Here's what the debugger says (the vertexStride and VertexBuffer has 24 which is the same size as the vertexData so it should be ok)
12
How do I stop stretching during window re size in XNA? In my windowed mode XNA game when the user resizes the window the game stops updating the window and the last frame drawn is stretched and distorted until the user releases the mouse and the resize completes. Is there any way to have the game continue to run "normally", updating frames and redrawing the screen, during the resize event? I realize that keeping the render loop going while resizing may not be possible or recommended due do hardware managed resources getting continually created and destroyed, but is there any way to stop the ugly stretching? Ideally by leaving the existing frame unscaled in the top left, or with a black screen if that isn't possible.
12
Learning Web Development and Game Development at the same time? I'm a junior level developer, currently working full time and trying to get experience with working with ASP.NET MVC. I love web development, and want to continue to pursue it as my career, but I also love gaming and have done a few game tutorials with Monogame XNA, and love that as well. For anyone that has been in this situation, Can you tell me, from experience, if you noticed any form of degenerative results when trying to split focus between a full time career in another field and beginning game development? I am looking for concrete examples of people who managed to split their time, and what their experience was like. I'm concerned that if I focus on game development on my spare time, then my growth in web development might suffer. I hope to use your input to determine for myself, how I should split up my free time, and manage my "Extracurricular" web projects, AND game development projects, so that I don't end up as a jack of all trades, master of none. I don't know why this is such a hard decision for me. (
12
Write alpha channel into SurfaceFormat.Single rendertarget in XNA HLSL I need to initialize a rendertarget ('SurfaceFormat.Single' format) drawing sprites into it. I would like the alpha channel of the sprite to be written into the rendertarget, so that regardless of the sprite texture, i end up with sprites silhouettes in the rendertarget. But XNA doesn't support alpha blending when using SurfaceFormat.Single, and from the pixel shader in which i handle the rendertarget for further calculations, i have all 0 readings. I find documentation of this features to be sparse and partial, so, could anyone suggest some source where i can check the sanity of my code?
12
Unable to generate standalone noise I've been stuck this evening on getting a Perlin Noise function to generate by itself. Every time I run the program without adding to different types of noise together it calls an ArgumentException error. Here is my code I'm using. perlin gen Random rand new Random() double freq 1 32.0 double lacu 3.0 int octave 5 double pers 0.5 int seed 1 Perlin perlin new Perlin(freq, lacu, pers, octave, seed, QualityMode.High) init the noise map noiseMap new Noise2D(128, 128) noiseMap.GeneratePlanar(1, 2, 1, 2, true) And the error that it calls is here. public void GeneratePlanar(double left, double right, double top, double bottom, bool seamless) if (right lt left bottom lt top this.m generator null) throw new ArgumentException() I've checked and re checked the code multiple times, so I'm not sure what is going on that is making the GeneratePlanar function call the ArgumentException error.
12
How do I make a resolution independent system? I'm blanking on this one. I can anchor stuff on edges of course, that would make my UI resolution independent...until it changes so much that the graphics are too small. How do I scale appropriately whenever needed? How do I keep my graphics at the right proportion while scaling? I don't want them stretched if the resolution has a different proportion like 16 10 as opposed to whatever else. Is there a true and tested approach to this? Video players show black borders because of this problem, is this not properly solvable?
12
MonoGame game running slowly Through development I've been running my 2D game (Monogame 3.6) on my windows laptop, which has some crummy integrated graphics card and an i5. Now I try my game on my gaming PC, which has a GTX 970 and also an i5 (a slightly better one), and the game runs slow as hell. I'm at a complete and total loss here. Here's what I've tried to speed up the game, and it's still hovering around maybe 15 FPS Reducing the game from 3 or 4 spritebatch blocks to a single one Removing ALL shader uniform changes, so that it only sets up the shader uniforms once and never changes them Commenting out 100 of particle rendering code. Removing my extra render target that I used for post process fx. After all of this, making it about as simple as a Hello World renderer, and it's still dog slow. I'm dumbfounded. Codetrack profiler says 80 of my cpu time is inside of a function called DoDraw which seems to be XNA framework code. So I'm sure it's not the update logic, or sheer number of things rendering, etc. The time anything is taking pales in comparison to DoDraw. The stack looks like this Tick DoDraw Present PlatformPresent But I don't really understand what it's doing and why it's taking so long. Any tips, knowledge of rendering quirks, profiling tips, etc, anything appreciated.
12
Farseer and 2D Action sidescroller game I'm thinking about using Farseer inside my game (I'm not good in physics), which isn't a bad idea. However something happened while I was thinking about that, I found this tutorial http www.sgtconker.com 2010 09 article xna farseer platform physics tutorial which talks about how to use Farseer, expecially the first part shows how to create a good collision method with a static object (like ground!!!), which, partially answer to my old question 2D Side Scrolling game and quot walk over ground quot collision detection So, is a good idea to use a physics engine to create a "walkable" terrain in a game? (obviusly I will use it for jumps and other things too) Is it a bit exaggerated, I mean, does it creates performance issues if I use it for something like ground collision which happens all time (except when jumping) in a game? If it's ok I've solved 2 questions with 1! Thanks for suggestions.
12
XNA positioning after rotation I have a turret with a 2 gunbarrels. The turret rotates towards my mouse. So far no problem. When it creates a few bullets and positions them at the end of the gun barrels. Here is the problem. It only works the moment the gun is point upwards. The moment it rotates the end of the gun barrels have moved ofcourse, thus the bullets don't spawn at the end of the gun battels, but at the place the where the gun barrels are when the turret is pointing upwards. How can I check where the end of the gun barrels are the moment it rotates? EDIT With the following code it positions the bullet next to turret, not at the end of the gun barrels. To see what I mean Vector2 bulletPosition new Vector2() bulletPosition.X (float)((Math.Cos( rotation)) barrelLenght) position.X bulletPosition.Y (float)((Math.Sin( rotation)) barrelLenght) position.Y rotation the angle the turret is rotated at. barrelLenght the length of the barrels. position the position of the turret. EDIT 2 With this code I get the bullets right between the 2 gun barrels. bulletPosition.X (float)((Math.Cos( rotation (float)(Math.PI 2))) barrelLenght) position.X bulletPosition.Y (float)((Math.Sin( rotation (float)(Math.PI 2))) barrelLenght) position.Y With this code I get the 2 bullets at the right end of the gun barrels, but only when the turret is pointing upwards. bulletPosition.X (float)((Math.Cos( rotation (float)(Math.PI 2))) barrelLenght) position.X bulletSpawn.X bulletPosition.Y (float)((Math.Sin( rotation (float)(Math.PI 2))) barrelLenght) position.Y bulletSpawn.Y I have to get the bulletSpawn relative to the end of the gun barrels position. EDIT THE FIX I FOUND I found a fix that worked Create Matrix with rotation value Matrix rotationMatrix Matrix.CreateRotationZ( rotation) Create Vector2 with offset from turret center to end of barrel. Vector2 bulletPosition point Do a transform with the bulletPosition Vector2 and the rotationmatrix bulletPosition position Vector2.Transform( bulletPosition, rotationMatrix)
12
Applicability of Business Architectures in XNA 4 I've done a lot of C programming and the architecture we use of late is a MVC PresentationService Domain Service And OR DataService Repository with a UnitOfWork and a messaging bus. In web applications this gives a pretty clean and flexible design that's extensible but is also stateless. I've been working on a 2D starter project in XNA and I find these layers are still useful until I get to the interface and start trying to deal with knowing the states of everything, keeping the sprites and bounding rectangles and detecting clicks and drags. What patterns should I be looking at that maybe I just wasn't exposed to doing enterprise architecture but are clearly needed in a game. Which concepts might I need to let go of when doing a game because they are not applicable.
12
2D Tile Based Collision Detection There are a lot of topics about this and it seems each one addresses a different problem, this topic does the same. I was looking into tile collision detection and found this where David Gouveia explains a great way to get around the person's problem by separating the two axis. So I implemented the solution and it all worked perfectly from all the testes I through at it. Then I implemented more advanced platforming physics and the collision detection broke down. Unfortunately I have not been able to get it to work again which is where you guys come in )! I will present the code first public void Update(GameTime gameTime) if(Input.GetKeyDown(Keys.A)) velocity.X moveAcceleration else if(Input.GetKeyDown(Keys.D)) velocity.X moveAcceleration if(Input.GetKeyDown(Keys.Space)) if((onGround amp amp isPressable) (!onGround amp amp airTime lt maxAirTime amp amp isPressable)) onGround false airTime (float)gameTime.ElapsedGameTime.TotalSeconds velocity.Y initialJumpVelocity (1.0f (float)Math.Pow(airTime maxAirTime, Math.PI)) else if(Input.GetKeyReleased(Keys.Space)) isPressable false if(onGround) velocity.X groundDrag velocity.Y 0.0f else velocity.X airDrag velocity.Y gravityAcceleration velocity.Y MathHelper.Clamp(velocity.Y, maxFallSpeed, maxFallSpeed) velocity.X MathHelper.Clamp(velocity.X, maxMoveSpeed, maxMoveSpeed) position velocity (float)gameTime.ElapsedGameTime.TotalSeconds position new Vector2((float)Math.Round(position.X), (float)Math.Round(position.Y)) if(Math.Round(velocity.X) ! 0.0f) HandleCollisions2(Direction.Horizontal) if(Math.Round(velocity.Y) ! 0.0f) HandleCollisions2(Direction.Vertical) private void HandleCollisions2(Direction direction) int topTile (int)Math.Floor((float)Bounds.Top Tile.PixelTileSize) int bottomTile (int)Math.Ceiling((float)Bounds.Bottom Tile.PixelTileSize) 1 int leftTile (int)Math.Floor((float)Bounds.Left Tile.PixelTileSize) int rightTile (int)Math.Ceiling((float)Bounds.Right Tile.PixelTileSize) 1 for(int x leftTile x lt rightTile x ) for(int y topTile y lt bottomTile y ) Rectangle tileBounds new Rectangle(x Tile.PixelTileSize, y Tile.PixelTileSize, Tile.PixelTileSize, Tile.PixelTileSize) Vector2 depth if(Tile.IsSolid(x, y) amp amp Intersects(tileBounds, direction, out depth)) if(direction Direction.Horizontal) position.X depth.X else onGround true isPressable true airTime 0.0f position.Y depth.Y From the code you can see when velocity.X is not equal to zero the HandleCollisions() Method is called along the horizontal axis and likewise for the vertical axis. When velocity.X is not equal to zero and velocity.Y is equal to zero it works fine. When velocity.Y is not equal to zero and velocity.X is equal to zero everything also works fine. However when both axis are not equal to zero that's when it doesn't work and I don't know why. I basically teleport to the left side of a tile when both axis are not equal to zero and there is a air block next to me. Hopefully someone can see the problem with this because I sure don't as far as I'm aware nothing has even changed from what I'm doing to what the linked post's solution is doing. Thanks.
12
Effective SpriteBatching in XNA? What is an example of efficient sprite batching in XNA? I don't know when (if ever) I would do something like this spriteBatch.Begin() DrawSprite1() spriteBatch.End() spriteBatch.Begin() DrawSprite2() spriteBatch.End() Is there any time within a draw method that I would separate drawing calls like this? Thanks!
12
Isometric Collision Detection I am having some issues with trying to detect collision of two isometric tile. I have tried plotting the lines between each point on the tile and then checking for line intercepts however that didn't work (probably due to incorrect formula) After looking into this for awhile today I believe I am thinking to much into it and there must be a easier way. I am not looking for code just some advise on the best way to achieve detection of overlap
12
What is the future of XNA in Windows 8 or how will managed games be developed in Windows 8? 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.
12
Higher Performance With Spritesheets Than With Rotating Using C and XNA 4.0? I would like to know what the performance difference is between using multiple sprites in one file (sprite sheets) to draw a game character being able to face in 4 directions and using one sprite per file but rotating that character to my needs. I am aware that the sprite sheet method restricts the character to only be able to look into predefined directions, whereas the rotation method would give the character the freedom of "looking everywhere". Here's an example of what I am doing Single Sprite Method Assuming I have a 64x64 texture that points north. So I do the following if I wanted it to point east spriteBatch.Draw( sampleTexture, new Rectangle(200, 100, 64, 64), null, Color.White, (float)(Math.PI 2), Vector2.Zero, SpriteEffects.None, 0) Multiple Sprite Method Now I got a sprite sheet (128x128) where the top left 64x64 section contains a sprite pointing north, top right 64x64 section points east, and so forth. And to make it point east, i do the following spriteBatch.Draw( sampleSpritesheet, new Rectangle(400, 100, 64, 64), new Rectangle(64, 0, 64, 64), Color.White) So which of these methods is using less CPU time and what are the pro's and con's? Is .NET XNA optimizing this in any way (e.g. it notices that the same call was done last frame and then just uses an already rendered rotated image thats still in memory)?
12
How to position a Weapons model in a first person shooter with XNA I am building a first person shooter and positioning the weapons is hard. I am trying to get the bat to look like you are holding it but I keep trying things and they don't appear in the positions I want them to be in. Here is what I did with one version of the function. void DrawModelModel(Model model, Matrix world) Vector3 modelPosition Vector3.Zero float modelRotation 0.0f Viewport viewport graphics.GraphicsDevice.Viewport float aspectRatio (float)viewport.Width (float)viewport.Height Set the position of the camera in world space, for our view matrix. Vector3 cameraPosition new Vector3(0.0f, 0.0f, 200.0f) Copy any parent transforms. Matrix transforms new Matrix model.Bones.Count model.CopyAbsoluteBoneTransformsTo(transforms) Draw the model. A model can have multiple meshes, so loop. foreach (ModelMesh mesh in model.Meshes) This is where the mesh orientation is set, as well as our camera and projection. foreach (BasicEffect effect in mesh.Effects) effect.World transforms mesh.ParentBone.Index Matrix.CreateRotationY(modelRotation) Matrix.CreateFromYawPitchRoll(0.0f, 1.0f, 1.0f) effect.View Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up) effect.Projection Matrix.CreatePerspectiveFieldOfView( MathHelper.ToRadians(35.0f), aspectRatio, 1.0f, 10000.0f) Draw the mesh, using the effects set above. mesh.Draw() Here is what I did with a different version of the function. void DrawModelModel(Model model, Matrix world) Vector3 modelPosition Vector3.Zero float modelRotation 0.0f Viewport viewport graphics.GraphicsDevice.Viewport float aspectRatio (float)viewport.Width (float)viewport.Height Set the position of the camera in world space, for our view matrix. Vector3 cameraPosition new Vector3(0.0f, 0.0f, 200.0f) Copy any parent transforms. Matrix transforms new Matrix model.Bones.Count model.CopyAbsoluteBoneTransformsTo(transforms) Draw the model. A model can have multiple meshes, so loop. foreach (ModelMesh mesh in model.Meshes) This is where the mesh orientation is set, as well as our camera and projection. foreach (BasicEffect effect in mesh.Effects) effect.World transforms mesh.ParentBone.Index Matrix.CreateRotationY(modelRotation) Matrix.CreateFromYawPitchRoll(0.0f, 1.0f, 1.0f) effect.View Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up) effect.Projection Matrix.CreatePerspectiveOffCenter( 2.0f,1.0f, 0.0f, 1.0f, 1.0f, 10000.0f) Draw the mesh, using the effects set above. mesh.Draw() What matrix can I use to get the bat model to appear realistically as if you are really holding it in a first person view. I am new to matrices so my knowledge of them is basic. What matrix should I use or what parameters with my current matrix should I be editing? I am thinking the projection matrix is what I need to be editing, but I am very confused at this point. Any help would be great.
12
Does XNA provide any special class to make a game server? For my multiplayer game server, I made a class inheriting from "Microsoft.Xna.Framework.Game", just like I did for the client side part. The thing is, I don't need any graphical display for the server, so I end up with a useless blank game window floating around. Also, the LoadContent UnloadContent and Draw overrides are left empty. On the other hand, I still need to use Microsoft.Xna.Framework.Game for the game loop and logic update parts. So is there any special class in XNA made especially for the server side part, or is everyone else doing it just like I do?
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
How to import fbx into XNA? I am developing basic XNA car game. I used 3D fbx car models to represent car objects. I drag and drop all tga and fbx files into content and I succesfully showed car in my game by using some basic codes. But the problem is when I move the car around the components move around irrelevant because some components of fbx model have different X, Y, Z directions according to world. I tried a lot of fbx models but all of it same. Also the colors have not shown on game. What is the solution of this broblem. How can I equal all component axes to game world axes to move around together? Why I can not see the colors of components?
12
Using shader for cubes I am trying to use a shader to get an effect like this. Notice how every cube has exactly the same lightning as every other no matter where it is on the screen if you look closely the lightning is making the front face's top parts darker, and the front face's lower parts lighter (about 20 difference at most) also more importantly the edges of the cubes are smoothed ( filleted ) and foggy looking I am drawing my cubes like this with the default lightning. cubeEffect.EnableDefaultLighting() for (int i 0 i lt 10 i ) for (int j 0 j lt 25 j ) apply the effect and render the cube foreach (EffectPass pass in cubeEffect.CurrentTechnique.Passes) cubeEffect.World Matrix.CreateTranslation( 15.6f i 3.05f, 15.5f j 1.168f, 0.0f) pass.Apply() draw RenderToDevice(GraphicsDevice) This is how my cubes looks like with the default lightning... i am trying to achieve an effect like the first image. I have no experience with lightning effects and how to do something like this so, i'd appreciate any help on how to get started. I used this http blogs.msdn.com b dawate archive 2011 01 20 constructing drawing and texturing a cube with vertices in xna on windows phone 7.aspx tutorial's help to draw this
12
Best practices in managing character states While in development of a character, I feel like I'm digging myself deeper into a hole every time I add more functionality to him, creating more bugs and it seems like my code is tripping over itself all over the place. What are the best practices when managing character states for a character that has a large selection of abilities and actions that they can perform, without their abilities interrupting each other and creating a mess overall?
12
Registering XNA Custom Pipeline A while back I was looking for a way to export load Models in XNA for animations. I took the advice from a comment, and tried using the "SkinnedModelProcessor" he linked me to. It worked great at home, but at school, I can't seem to get XNA to acknowledge that I have a custom pipeline in the solution. I've added the references to both the content project and the main project, but no luck. When I compile the example, Visual Studio complains that the content processor can't be found. When using my own project, Visual Studio doesn't have the custom Pipeline Processor as an option. When using the example, "SkinnedModelProcessor" is the value in the fields, but if I click on the combobox, that option isn't there, and VS still complains. Obviously this is a problem with how Visual Studio is configured, but I have absolutely no clue what I should do about it. Any suggestions guys? I guess I could build the code for animations at home, and not worry about it at school, but that sounds like the easy way out. walloftext Some notes that are probably worth mentioning Any settings that I apply are reset when I log out. Any changes to the C drive are reset when the computer shuts down. The project is stored on a network location, which has caused problems in the past, evidently. ( Although, I personally don't know what these problems would include ).
12
A comparison of graphics libraries and their respective programming languages A comparison of graphics libraries and their respective programming languages. A.K.A. "Which do I pick? With a twist." I'm a long time professional programmer who never gave up on programming as a hobby. 3D programming has always appealed to me, but after some trial and error I always came back to (and got stuck on) the same question Which to choose? C with XNA. C with DirectX. Java with OpenGL. All three appeal to me XNA, because it's managed, of high quality and very complete. DirectX, because it's de facto standard for large games. OpenGL, because it's open. It has a proven track record of high quality games built using it. Eclipse hotswap functionality is sexy. Keep in mind here that I will Use the above library and language for hobby use. Will want to develop both 3D games and 3D tooling. Might seek a job in a 3D programming industry. For the sake of the argument, assume I am equally well versed in C , C and Java. And have no preference for any of the three mentioned libraries. In reality I have a slight preference for one of those three, but the quality of the code I produce in the languages is the same. Replies with sources as links are preferred! OGRE and Irrlicht (and similar) are also contenders, but not preferred because it introduces additional depencies on other developers.
12
Is it possible to animate the texture of a model? Below is how far I've got. I just made a simple block with user primitives to test it. But I haven't found a way to crop the spritesheet. textureLava frames activeFrame This line is how I want it but off course this doesn't work. Is there a way to crop this spritesheet or is there another way to animate the texture of a model? public void CreateFrames() for (int i 0 i lt 64 i ) frames.Add(new Rectangle(WIDTH i, i, WIDTH, HEIGHT)) public override void Update(GameTime gameTime) if (System.Environment.TickCount lastFrameTime gt TIME BETWEEN FRAMES) activeFrame lastFrameTime System.Environment.TickCount if (activeFrame gt 15) activeFrame 0 textureLava frames activeFrame gt DOESN'T WORK base.Update(gameTime) public override void Draw(GameTime gameTime) effect.TextureEnabled true effect.World Matrix.Identity effect.View Camera.ActiveCamera.View effect.Projection Camera.ActiveCamera.Projection effect.Texture textureLava foreach (EffectPass pass in effect.CurrentTechnique.Passes) pass.Apply() GraphicsDevice.SetVertexBuffer(vertexBuffer) GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, 10)
12
How do I make Windows store recognize multiple resolutions? I'm currently developing a XNA Game for Windows phone 8, it works with every emulator resolution (WXGA, WVGA, 720p). However, when I upload the XAP to the Windows phone store it tells me that only WVGA resolution was detected. Do I have to add some code to make the app downloadable for WXGA phone owners ?
12
Can't change the textures of a .FBX or an .X exported from 3dsmax I created a model (real simple) in 3DSMax 2010, exported it to FBX format and loaded it in an XNA 4.0 content project. I also tried with .X files using kW X port and it has the same behavior. I can load the model in a game, and it has it's 3DSMax texture. I can't however change the texture of a face (or all) at runtime. When I do this, it doesn't crash or anything, it just doesn't apply the textures. I've tried with a sample model from a microsoft creative tutorial (the famous spaceship one) and on that model, with my texture, it works. This is why I think my model isn't working properly. Anyone care to comment help? Note Even though I don't think the problem is there since I've made it work with another model, here is my LoadContent method to load the model and change the texture of all mesh protected override void LoadContent() base.LoadContent() ContentManager contentManager new ContentManager(Game.Services, "Content") Model (Model)contentManager.Load lt Model gt (ModelName) Texture (Texture2D)contentManager.Load lt Texture2D gt (TextureName) foreach (ModelMesh mesh in Model.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.Texture Texture
12
Create random level platforms on screen I'm trying to create random level platforms like this public Level(int platfromsInLevel, Texture2D sprite, int screenWidth) rnd new Random() this.screenWidth screenWidth for (int i 0 i lt platfromsInLevel i ) if (i 0) Platform platform new Platform((new Vector2(0, 0)), (new Vector2(0, 0)), sprite) Platformlist.Add(platform) else int CurrentX (int)Platformlist i 1 .getPos().X Platformlist i 1 .getTex().Width int CurrentY (int)Platformlist i 1 .getPos().Y Platformlist i 1 .getTex().Height int xRand rnd.Next(CurrentX 100,(CurrentX 100) 150) int yRand rnd.Next(CurrentY 200, (CurrentY 200) 200) if (xRand lt screenWidth xRand gt 0) Platform platform new Platform((new Vector2(0, 0)), (new Vector2(xRand, yRand)), sprite) Platformlist.Add(platform) Can anyone help with the random logic? I only want them to appear on the screen that is visible on the X axis, but the y axis is infinite it can go as high as needed. The width of the screen is stored in screenWidth. I also don't think my random logic is taking into account the whole screen width, it only adds positive values. Finally I've tried to add some logic that says a platform can only be a certain height and distance away from another one whilst taking into account the previous platforms position, but its not really working. Anyone got any ideas to tidy this up a little bit?
12
Closest point on an ellipsoid I need to know how to get the closest point on the surface of an ellipsoid to another point. I had an idea, but apparently i was wrong, and oversimplfying. What i did was squash the ellipsoid and point into local space, so the ellispoid is a unit circle vector3 pointLocalCoord ( pointOriginal ellipsoid.origin ) ellipsoid.radii Then from there, the closest point should be 1, in the direction of the transformed point from the origin vector3 closestPointOnEllipsoidLocal norm ( pointLocalCoord ) Then get back into standard space vector3 closestPointOnEllipsoidWorld closestPointOnEllipsoidLocal ellipsoid.radius ellipsoid.origin But of course, all of this seems not to work, i was curious if any body could point me in the direction of some pre existing code or such as some of the articles i've tried reading kinda go a bit out of my scope of knowledge. Also, if that seems right to you, please do tell. I'm pretty sure its wrong though. Edit Sorry for the unresponsiveness with this and my other question. They're different, i was axperimenting with something else
12
Dynamically Discovering Game Content I am trying to determine the best way to dynamically discover new levels in my Windows Phone game. This is necessary because I will be selling some levels separately to those included with the initial game purchase. I assume that it is possible for such purchases to be automatically downloaded and merged into the same directory that contains the game itself. All my levels are pre processed and stored as XNBs. Ideally, I would be able to obtain an enumeration of all XNBs of a particular type (ie. Level) within my game directory, but I cannot find a means of doing this. Alternatively, if I could get a list of all XNB names then I could use a naming convention to identify levels. Unfortunately, I can't find a way to do that either. Am I barking up the wrong tree here? Can anyone shed any light on how I might dynamically discover content in my game?
12
RPG like hit points growth algorithms help I am currently making an XNA game in C . I want to increase health as the player level up. I am currently using this equation. MaxHealth Convert.ToInt32(100 Math.Pow(1.17, level 1)) Its fine before the first 20 levels, but afterwards the health starts to increase extremely fast Level 1 100 Hp. Level 20 1.975 Hp. Level 30 9.493 Hp. Level 40 45.630 Hp. Level 100 658.546.089 Hp. Level 109 Crash value too big for an integer. How should i create these growth algorithms, so that the growth of hit points pr. level, will increase slowly. This is just an example, if you know a better growth rate, I will be happy to know that too. level 2 Hp base health 60 (Base health 100) level 3 Hp base helath 60 120 level 4 Hp base helath 60 120 180. But the max health formular will run on every update tick, so all this should happen in the same calculation. Edit Thank you all for your input, I really appreciate it. But while away from the question, I found a solution myself. Thank you very much. The solution if (level lt 35) this.baseMaxHealth Convert.ToInt32((vitality 10) Math.Pow(level, 2) 4) else this.baseMaxHealth Convert.ToInt32((vitality (level 25)) Math.Pow(level, 2) 4) I added vitality as an upgrade you can spend skill points or something on EDIT 2 I improved the code a bit if (level lt 35) this.baseMaxHealth Convert.ToInt32((vitality 10) Math.Pow(level, 2) 4) else if (level gt 125) this.baseMaxHealth Convert.ToInt32((vitality 100) Math.Pow(level, 2) 4) else this.baseMaxHealth Convert.ToInt32((vitality (level 25)) Math.Pow(level, 2) 4)
12
Farseer Shooting a ball in a certain angle? How can I shoot a ball in a certain angle? When I press the Space key, the ball should be shot in a 45 degree angle. How can I do that?
12
Sounds categories volume level in xna I am preparing sounds system to my game in xna. I am using XACT Tools, and i got problem. There is class SoundCategory. I can change sound level for all sounds in that category easily. SoundCategory category engine.GetCategory("music") category.SetVolume(float value) But there is no such function like category.AddVolume(float value) Which would increase or deacrease that value. There is also no function that get current volume so i can do thing like float vol category.Add(float value) vol 0.1 category.SetVolume(vol) Is there some clever way to achive what i want without creating some additional variables which keep current volume for all sounds categories ?
12
Is this way of making an XNA game window borderless safe to use for various Windows PCs? I have found a way to simply make an XNA 4.0 game's window borderless. Here is the code from the article IntPtr hWnd this.Window.Handle var control System.Windows.Forms.Control.FromHandle( hWnd ) var form control.FindForm() form.FormBorderStyle System.Windows.Forms.FormBorderStyle.None form.WindowState System.Windows.Forms.FormWindowState.Maximized You add it to the Game's constructor and it works perfectly. I tested it on several Windows PCs and it's great the game runs seemingly in full screen, even if you set the game's resolution lower higher than your desktop one. The only issue I had with it is the fact that you need to provide positions for XNA's SpriteBatch methods (Draw and DrawString) in desktop resolution, not in game's resolution, while retrieving width height from GraphicsDevice gives you the latter. At the same time, DOTA 2 has borderless window option, but the game scales the window down, if your requested in game resolution is lower than your desktop one. I wonder if they have a good reason for doing this? I wanted to ask if this approach is safe to use on PC or can it be buggy occasionally? I would especially like to know if it will work with Windows XP as I don't have a pc with this system to test it.
12
Collision detection against specific sprite shape using XNA with Farseer Physics? I am making a 2D XNA Game, using Farseer Physics for collisions. I need collisions to be resolved against the actual shape of the sprite image, ignoring transparent pixels, rather than against the edge of the bounding rectangle.
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
how to rotate enemy to face player? Okay so i havebeen rotating my enemy to face the player using float targetrotation Math.Atan2(playerpos enemypos) enemy.rotation targetrotation ( lt this line of code i want to change) This simple method has worked fine so far for getting the enemy to look at the player's position. However i decided to add some extra code to get the enemy to gradually rotate towards the player using this method if(enemy.rotation lt targetrotation) enemy.rotation if(enemy.rotation gt targetrotation) enemy.rotation Now the problem i am having is that when the player moves for example from 360 degree target to 1 degree then the enemy rotates the long way round to move to the 1 degree instead of simply adding 1 degree. Any help on how to correct this problem would be welcomed. I have a picture below
12
Grid based collision How many cells? The game I'm creating is a bullet hell game, so there can be quite a few objects on the screen at any given time. It probably maxes out at about 40 enemies and 200 or so bullets. That being said, I'm splitting up the playing field into a grid for my collision checking. Right now, it's only 8 cells. How many would be optimal? I'm worried that if I use too many, I'll be wasting CPU power. My main concern is processing power, to make the game run smoothly. RAM is not a big concern for me.
12
Coordinates from 3DS Max to XNA 3.5 My problem is this. I have a simple box made in 3DS Max 2009, the Box is 10x10x10. I've tried to load it on XNA and traslate the camera for 15 units, but I can seem to find the values needed to see the box properly. Can anyone point me to a good resource where I can find some good introduction to XNA coordinate system and how is a simple box made in 3DS Max imported properly Best regards, David
12
Determining my playable area field of view Contrary to what I found searching for the answer, I'm not trying to see whether a character is in view of another character. What I need to find out is the size of the field of view. This is because I'm using Mercury Particle Engine in a 3D space, and while MPE emitters take parameters ranging from (0,0) being the upper left corner of the screen to (graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight) being the lower right corner of the screen, the positioning of enemy ships use Vector3 values, where (0,0,0) would be the exact center of the screen. Since my ships don't move along the Z axis, this isn't a problem. What is a problem, however, is translating their coordinates in 3D space to the correct particle emitter positions when I need to show them exploding. This is what I'm currently using to create the perspective field of view projectionMatrix Matrix.CreatePerspectiveFieldOfView( MathHelper.ToRadians(45.0f), GraphicsDevice.DisplayMode.AspectRatio, 1250.0f, 1450.0f) And this is how I'm attempting to obtain the X and Y values for the particle emitter from the enemy ship position (however, the positions are not quite right with my math because I have the wrong constants) x ((float)graphics.PreferredBackBufferWidth 2) (((float)graphics.PreferredBackBufferWidth 1700) enemy i .position.X) y ((float)graphics.PreferredBackBufferHeight 2) (((float)graphics.PreferredBackBufferHeight 1100) enemy i .position.Y) That being said, how do I calculate the proper constants from the information on hand?
12
Confused about Content Pipeline I'm attempting to get my head around the XNA content pipeline, and how I can use it to simplify my game code. Specifically, I want to define sprites, sprite sheets, and animations as assets and have them automatically available to me in game code. At the end of the day, this is what I want to be able to do add a new file with .sprite extension to my content project call contentManager.Load lt Sprite gt ("NameOfSprite") and get back a Sprite instance My Sprite class looks like this public class Sprite public Texture2D Texture get ... public Rectangle? SourceRectangle get ... public Vector2 Origin get ... The purpose of the Origin property is not important it's specific to my game. The point is, I want it to be "packaged up" alongside the texture information. I've defined a SpriteData class as public sealed class SpriteData public string TextureFilename get set public Rectangle? SourceRectangle get set public Vector2 Origin get set And I've added a test.sprite file to my content project as lt ?xml version "1.0" encoding "utf 8" ? gt lt XnaContent xmlns data "MyNamespace" gt lt Asset Type "data SpriteData" gt lt TextureFilename gt Sprites Test.jpg lt TextureFilename gt lt SourceRectangle gt 0 5 20 25 lt SourceRectangle gt lt Origin gt 30 2 lt Origin gt lt Asset gt lt XnaContent gt I have defined a SpriteImporter as ContentImporter(".sprite", DisplayName "Sprite Importer", DefaultProcessor "SpriteProcessor") public class SpriteImporter ContentImporter lt SpriteData gt public override SpriteData Import(string filename, ContentImporterContext context) using (var xmlReader XmlReader.Create(filename)) return IntermediateSerializer.Deserialize lt SpriteData gt (xmlReader, filename) And a SpriteProcessor as ContentProcessor(DisplayName "Sprite Processor") public class SpriteProcessor ContentProcessor lt SpriteData, SpriteData gt public override SpriteData Process(SpriteData input, ContentProcessorContext context) var spritePath Path.GetDirectoryName(context.OutputFilename) var textureReference new ExternalReference lt Texture2DContent gt (input.TextureFilename) make sure the texture is built (not sure what else to do here) context.BuildAsset lt Texture2DContent, Texture2DContent gt (textureReference, string.Empty) return input Now I'm stuck. If I don't implement a content writer reader combination then I won't get a Sprite out of the content manager I'll get a SpriteData instead, which is not what I want. But my attempt to implement a SpriteWriter came up short. I have no idea how to get the texture information from the processor to the writer. Do I need to change the type from SpriteData to something else? Is there a sample anywhere that demonstrates how to do this end to end?
12
Rotations and angular velocity I'm new to 3D game programming and I'm having some trouble making objects rotate the way I want them to. I just read Glenn Fiedler's tutorials on game physics, awesome stuff by the way! (http gafferongames.com game physics physics in 3d ) Now, I'm trying to make a simple space sim. If you imagine a spaceship that is not yet rotated in any way (up Vector3.Up etc..). If I apply some yaw input (which would increase the angular velocity) I'd then expect the ship to rotate around the up vector of the ship (which is also the world y axis at the moment). That works fine. If I would then roll the ship a little bit, I'd expect the ship to roll around its forward axis, but it should also continue to spin around the world y axis. At the moment with my implementation instead of keeping it's momentum around the y axis, it continues to spin around its local up vector which is obviously wrong. I think I understand why this happens with my current implementation, I'm just not sure how to fix it. This is what I have at the moment, with some minor simplifications (runs every update) Vector3 addedRotation new Vector3(pitchInput, yawInput, rollInput) addedRotation Vector3.Transform(addedRotation, rotation) rotationVelocity addedRotation rotation.Normalize() Quaternion w new Quaternion(rotationVelocity, 0) rotation Quaternion.Multiply(w rotation, 0.5f) I'd be very happy if someone could point me in the right direction here. If anything needs clarification, please tell me and I'll try explain it better. Thanks for taking the time!
12
XNA My bullets lag the game the first time they're fired, but not after I'm working on a SpaceWar esque project to get comfortable with XNA. I have a Ship DrawableGameComponent and a Bullet DrawableGameComponent. The player's Ship is created at the start of the game, and the Bullets are created for each Ship as part of its constructor. In my Ship constructor, I have the following code for (int i 0 i lt 5 i ) activeBullets i new Bullet(game) The relevant part of my Ship's shoot() function is as follows activeBullets bullet .Visible true activeBullets bullet .Enabled true activeBullets bullet .position this.position The first five times I shoot() (that is, once for each bullet object that the ship is allotted), there is lag that I think is due to the bullet sprite being loaded. I've tried setting Visible and Enabled to true in the ship constructor loop where the Bullets are instantiated, but the first five shots lag persists. Any shots beyond the first five are completely lag free. How do I load the Bullets properly ahead of time so that there is no lag on the first shots?
12
How can I simulate shattering glass? I need to make a simulation with stone thrown through a glass window. How can I accomplish that? I mean, I was thinking about making a 3D model of a stone and glass in 3D Studio Max 2012, shatter the glass and export both to XNA 4.0 as .x models. Then in XNA make the animation writing my own physics engine. Is it possible that way? Is it possible to destroy the glass in XNA after impact or should I do it in 3DS Max? By 'destroying the glass' I mean disconnect some previously shattered glass bits from each others, because depending on the start speed and weight of the stone and resistance (hardness?) of the glass (all user defined) the bits will disconnect from each other in different ways.
12
Why does changing the diffuse color of my model's effect change it for all models? I want to change color of individual model in my game. But when I use effect.DiffuseColor newColor then all of models which were loaded from same model file change color too. How can I do ?
12
How can I compute a velocity proportional to the difference between two hand positions? I'm working on a project with the Kinect SDK and XNA 4. I need take the position of the hands and draw a sprite over it. I'm was doing it directly and because of that I get a "trembling hands" effect. So, I was thinking of making the sprite move from the previous position to the new one given in every frame by the new hand position. This way, the sprite does not jump from one position to another. This is working just fine, but I'm using a constant value for the velocity, and I really would like to use a variable velocity given by the difference between the previous and the new position. That is if the hand move more quickly in the reality, the velocity will be higher. I really don't have a clue on how to make this work. Can somebody point me in the right direction?
12
Sampler referencing in HLSL Sampler parameter must come from a literal expression The following method works fine when referencing a sampler in HLSL float3 P lightScreenPos sampler ShadowSampler DPFrontShadowSampler float depth if (alpha gt 0.5f) Reference the correct sampler ShadowSampler DPFrontShadowSampler Front hemisphere 'P0' P.z P.z 1.0 P.x P.x P.z P.y P.y P.z P.z lightLength LightAttenuation.z Rescale viewport to be 0, 1 (texture coordinate space) P.x 0.5f P.x 0.5f P.y 0.5f P.y 0.5f depth tex2D(ShadowSampler, P.xy).x depth 1.0 depth else Reference the correct sampler ShadowSampler DPBackShadowSampler Back hemisphere 'P1' P.z 1.0 P.z P.x P.x P.z P.y P.y P.z P.z lightLength LightAttenuation.z Rescale viewport to be 0, 1 (texture coordinate space) P.x 0.5f P.x 0.5f P.y 0.5f P.y 0.5f depth tex2D(ShadowSampler, P.xy).x depth 1.0 depth Standard Depth Calculation float mydepth P.z shadow depth Bias.x lt mydepth ? 0.0f 1.0f If I try and do anything with the sampler reference outside the if statement then I get the following error Sampler parameter must come from a literal expression This code demonstrates that float3 P lightScreenPos sampler ShadowSampler DPFrontShadowSampler if (alpha gt 0.5f) Reference the correct sampler ShadowSampler DPFrontShadowSampler Front hemisphere 'P0' P.z P.z 1.0 P.x P.x P.z P.y P.y P.z P.z lightLength LightAttenuation.z else Reference the correct sampler ShadowSampler DPBackShadowSampler Back hemisphere 'P1' P.z 1.0 P.z P.x P.x P.z P.y P.y P.z P.z lightLength LightAttenuation.z Rescale viewport to be 0, 1 (texture coordinate space) P.x 0.5f P.x 0.5f P.y 0.5f P.y 0.5f Standard Depth Calculation float depth tex2D(ShadowSampler, P.xy).x depth 1.0 depth float mydepth P.z shadow depth Bias.x lt mydepth ? 0.0f 1.0f How can I reference the sampler in this manner without triggering the error?
12
A big light with shadows To have better texture2D quality in my 2D game, I had to recreate every textures with 300 of their original size. But the lights have to bright 3 times more. For lights, I'm using this Catalin's blog I have to render some lights, but with only 1 with 800 pixels of radius, my game works with around 15fps or less. And if I improve the light quality, I have an issue with the (gpu ?) memory. How must I do to render a light with 800 pixels of radius without this gpu cost ? Should I use another effect ? Do you have some to suggest ? (example Andrew Russell's game "Dark" has a lots of big lights, and the game works perfectly) Hope you can help.