_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
12 | How Do I Do Alpha Transparency Properly In XNA 4.0? Okay, I've read several articles, tutorials, and questions regarding this. Most point to the same technique which doesn't solve my problem. I need the ability to create semi transparent sprites (texture2D's really) and have them overlay another sprite. I can achieve that somewhat with the code samples I've found but I'm not satisfied with the results and I know there is a way to do this. In mobile programming (BREW) we did it old school and actually checked each pixel for transparency before rendering. In this case it seems to render the sprite below it blended with the alpha above it. This may be an artifact of how I'm rendering the texture but, as I said before, all examples point to this one technique. Before I go any further I'll go ahead and paste my example code. public void Draw(SpriteBatch batch, Camera camera, float alpha) int tileMapWidth Width int tileMapHeight Height batch.Begin(SpriteSortMode.Texture, BlendState.AlphaBlend, SamplerState.PointWrap, DepthStencilState.Default, RasterizerState.CullNone, null, camera.TransformMatrix) for (int x 0 x lt tileMapWidth x ) for (int y 0 y lt tileMapHeight y ) int tileIndex map y, x if (tileIndex ! 1) Texture2D texture tileTextures tileIndex batch.Draw( texture, new Rectangle( (x Engine.TileWidth), (y Engine.TileHeight), Engine.TileWidth, Engine.TileHeight), new Color(new Vector4(1f, 1f, 1f, alpha ))) batch.End() As you can see, in this code I'm using the overloaded SpriteBatch.Begin method which takes, among other things, a blend state. I'm almost positive that's my problem. I don't want to BLEND the sprites, I want them to be transparent when alpha is 0. In this example I can set alpha to 0 but it still renders both tiles, with the lower z ordered sprite showing through, discolored because of the blending. This is not a desired effect, I want the higher z ordered sprite to fade out and not effect the color beneath it in such a manner. I might be way off here as I'm fairly new to XNA development so feel free to steer me in the correct direction in the event I'm going down the wrong rabbit hole. TIA |
12 | Exporting .FBX model into XNA unorthogonal bones I create a butterfly model in 3ds max with some basic animation, however trying to export it to .FBX format I get the following exception.. any idea how i can transform the wings to be orthogonal.. One or more objects in the scene has local axes that are not perpendicular to each other (non orthogonal). The FBX plug in only supports orthogonal (or perpendicular) axes and will not correctly import or export any transformations that involve non perpendicular local axes. This can create an inaccurate appearance with the affected objects Right.Wing I have attached a picture for reference . . . |
12 | Mouse state not acting as I intend it to I am creating an inventory system. I have it working well, but for some reason when I pick up an item from a slot(lets say slot 2 of 20) and drop it into that same slot(slot 2) the mouse state fails to update correctly, resulting in the item being dropped and picked back up in the same cycle. I feel like I am missing something here, but would appreciate any help. Below is my code. The method that controls the Item being Dropped into the inventory public void ItemDropped(Vector2 pos, Item item) for (int intlc 0 intlc lt InvBoxes.Count intlc ) if (InvBoxes intlc .Intersects(new Rectangle((int)pos.X, (int)pos.Y, 1, 1))) if (Items intlc ! null) ClampedItem Items intlc else Set bln in Game to stop drawing item at cursor ClampedItem null GlobalVariables.TheGame.blnClamp false Items intlc item break Logic in my Inventory Class' Update method to Update the mouse state, after setting the old mouse state. Then it check for hovering over an item, and sets all old hovers to false. It then looks for if I am clicking on the item hovered over, and therein lies the problem oms ms ms Mouse.GetState() set hover for (int intlc 0 intlc lt Items.Count intlc ) if (Items intlc ! null) if ((ms.X Items intlc .location.X) lt 50 amp amp (ms.X Items intlc .location.X) gt 0 amp amp (ms.Y Items intlc .location.Y) lt 30 amp amp (ms.Y Items intlc .location.Y) gt 0) Items intlc .invhover true else Items intlc .invhover false for (int intlc 0 intlc lt Items.Count intlc ) if (Items intlc ! null) if (Items intlc .invhover) if (ms.LeftButton ButtonState.Pressed amp amp oms.LeftButton ButtonState.Released) ClampedItem Items intlc Items intlc null GlobalVariables.TheGame.blnClamp true In my game Class at the end of the the Update I have a few calls that pertain to this issue Rectangle rect new Rectangle(mouseState.X, mouseState.Y, 1, 1) if (blnClamp) if (rect.Intersects(inventory.Bounds) amp amp mouseState.LeftButton ButtonState.Pressed amp amp MoldState.LeftButton ButtonState.Released) inventory.ItemDropped(new Vector2(mouseState.X, mouseState.Y), inventory.ClampedItem) inventory.Update(InvPos) If you look at the conditional in my game's inventory's Update method's check for mouse state's current and old button state being pressed and released, when I grab an item from slot 1 and drop it into slot 2, the mouse state conditional validate as intended. But when trying to grab the item at slot 1 and drop it back into slot one, the item drops, and is immediately clamped again because old mouse state is up and new mouse state is down. Both instances will hit the conditional that is inside the hover conditional. Additional Note When I put a breakpoint on the ItemDropped Method inside my inventory class, the debugger causes the mouse state to update as intended, and the item that I picked up out of slot 2 is placed into slot 2 without fail. There is a flaw programatically to how I have my updates set up somehow. |
12 | Loading a stream asset on Android MonoGame without ContentManager In the game I am developing, I have created a serializable class that generates a .map file for saving and loading levels. In XNA, this works great using the following code FileStream fileStream new FileStream(filePath, FileMode.OpenOrCreate) BinaryFormatter formatter new BinaryFormatter() MapInfo data (MapInfo)formatter.Deserialize(fileStream) Unfortunately, in android it appears that the filePath ends up at the device's root (argument being passed in as "Content maps"). After some research, I came across this page from xamarin that explains how to properly load assets from the asset folder. However, this action takes place in a separate namespace from my main activity, and so far have not found a way to access the Assets.Open() function. any other ways to load that asset? UPDATE After playing around some more, I ended up trying to pass the Assets property of the main activity down through function calls, loading the file this way Stream fileStream androidGame.Assets.Open(filePath) BinaryFormatter formatter new BinaryFormatter() MapInfo data (MapInfo)formatter.Deserialize(fileStream) SADLY, the file still does not load. Looking at the variables in debug shows the correct address for the activity contained in the variable androidGame, but says Open is an "Unknown member" UPDATE WITH WORKING SOLUTION In case anyone comes across file loading issues in Monogame Android, this is what I ended up doing First, make sure you copy reference your files in the correct dir of your android build. This should appear somewhere under Assets Content yourfile.file or subfolder. Then, check the properties of the file and select "AndroidAsset" for build options and "Copy if newer" for output. Finally, open the stream using the Assets property of your main activity. This can be accessed using your Microsoft.Xna.Framework.Game class in this way Stream fileStream Game.Activity.Assets.Open(path) Turns out my issue was not the stream itself, but the deserialization which could not open a .dll in android (overlooked that one...). I ended up switching to XML serialization, since the binary serialization is build dependent |
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 | 2D platformer corner collision Repost from my question on stack overflow, didnt know this site existed. I have a 2d platformer and I need help with collision. To show you my current collision system, here is picture Top picture is how game looks normally, bottom picture shows highlighted collision rectangles. Black ones are horizontal (If player rectangle intersects them, move player on Y axis), blue are vertical (move player on the X axis) and red are corners. I've implemented corner rectangles, after bit of testing after I found out, that when I had black and blue overlapping each other, this happened Player jumped and intersected both rectangles at once, game would recognize that and resolve both intersection at the same time, cause the player to spaz around the map and ending up in a another rectangle, which would then cause another intesection and resolution until the chain reaction stopped, and player would end up somewhere where he should not have been. So I added corner rectangles, they should resolve this situation like this if player hits corner from the bottom, act like horizotal rectangle, if he hits from side, act like vertical. Thing is, I have no idea how to make them work like that. Here is my code so far if (InputHandler.KeyDown(Keys.W)) player.MoveUp() Parallel.For(0, horizontalPlayerCollisionRectangles.Count, i gt if (player.PlayerRectangleInWorld.Intersects(horizontalPlayerCollisionRectangles i )) player.PlayerPositionY horizontalPlayerCollisionRectangles i .Y horizontalPlayerCollisionRectangles i .Height ) if (InputHandler.KeyDown(Keys.D)) player.MoveRight() Parallel.For(0, verticalPlayerCollisionRectangles.Count, i gt if (player.PlayerRectangleInWorld.Intersects(verticalPlayerCollisionRectangles i )) player.PlayerPositionX verticalPlayerCollisionRectangles i .X player.PlayerRectangleInWorld.Width ) if (InputHandler.KeyDown(Keys.A)) player.MoveLeft() Parallel.For(0, verticalPlayerCollisionRectangles.Count, i gt if (player.PlayerRectangleInWorld.Intersects(verticalPlayerCollisionRectangles i )) player.PlayerPositionX verticalPlayerCollisionRectangles i .X verticalPlayerCollisionRectangles i .Width ) if (player.Gravity) Parallel.For(0, horizontalPlayerCollisionRectangles.Count, i gt if (player.PlayerRectangleInWorld.Intersects(horizontalPlayerCollisionRectangles i )) player.PlayerPositionY horizontalPlayerCollisionRectangles i .Y player.PlayerRectangleInWorld.Height ) Its pretty simple. Now that I think about it, my system is flawed, so thats why I'm asking this question. How to make collision work using collision rectangles? P.S. I can't use any physics engine like Farseer, it's a school graduation project and I have to code as much as possible by myself. |
12 | Save Texture2D to file in Monogame I'm working on a tilesheet builder tool for my game to speed up tile creation, and I need to save a generated texture2D as a png. I've tried using the .SaveAsPng function but it isn't implemented in Monogame. Is there any way around this in monogame? EDIT I've tried this private void SaveTextureData(RenderTarget2D texture, string filename) byte imageData new byte 4 texture.Width texture.Height texture.GetData lt byte gt (imageData) System.Drawing.Bitmap bitmap new System.Drawing.Bitmap(texture.Width, texture.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb) System.Drawing.Imaging.BitmapData bmData bitmap.LockBits(new System.Drawing.Rectangle(0, 0, texture.Width, texture.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, bitmap.PixelFormat) IntPtr pnative bmData.Scan0 System.Runtime.InteropServices.Marshal.Copy(imageData, 0, pnative, 4 texture.Width texture.Height) bitmap.UnlockBits(bmData) bitmap.Save(filename) but it's giving a weird output, and I don't know why http i.imgur.com XT9Dnjj.png Thanks for any help! |
12 | Drawing Shape in DebugView As the title says, I need to draw a shape polygon in Farseer using debugview. I have this piece of code which converts a Texture to polygon load texture that will represent the tray trayTexture Content.Load lt Texture2D gt ("tray") Create an array to hold the data from the texture uint data new uint trayTexture.Width trayTexture.Height Transfer the texture data to the array trayTexture.GetData(data) Find the vertices that makes up the outline of the shape in the texture Vertices verts PolygonTools.CreatePolygon(data, trayTexture.Width, false) Since it is a concave polygon, we need to partition it into several smaller convex polygons list BayazitDecomposer.ConvexPartition(verts) Vector2 vertScale new Vector2(ConvertUnits.ToSimUnits(1)) foreach (Vertices verti in list) verti.Scale(ref vertScale) tray BodyFactory.CreateCompoundPolygon(MyWorld, list, 10) Now in DebugView I guess I have to use "DrawShape" method which requires DrawShape(Fixture fixture, Transform xf, Color color) My question is how can I get the variables needed for this method, namely Fixture and Transform? |
12 | Fire range arc behind buildings need some help with HLSL. Each charater in my game shows a fire range arc (which is a textured model) which show how far the guy can shoot, see It looks ok, but I hate the fact that it shows even behing buildings. Now I already have a shader for rendering the Arc (where I only manipulate the u coordinate to achive oscilating effect) and I'm pretty sure that I can use the Shadow map approach for that generate Shadow map as seen by the camera (my deferred renderer takes care of that), then when rendering the arc, compare current Depth to the one stored in shadow map and voila.. But I just can't get it to work. I know the theory, but I'm no expert in HLSL and shadow mapping... Here is the code I have ... float4x4 World float4x4 View float4x4 Projection float4x4 ObserverWVP of the character casting the arc texture DepthMap as seen by the camera ... struct VertexShaderInput float4 Position POSITION0 float2 TextureCoordinates TEXCOORD0 struct VertexShaderOutput float4 Position POSITION0 float2 TextureCoordinates TEXCOORD0 float4 Observer TEXCOORD1 VertexShaderOutput VertexShaderFunction(VertexShaderInput input) VertexShaderOutput output float4 worldPosition mul(input.Position, World) float4 viewPosition mul(worldPosition, View) output.Position mul(viewPosition, Projection) output.Observer mul(input.Position, ObserverWVP) output.TextureCoordinates input.TextureCoordinates return output float4 PixelShaderFunction(VertexShaderOutput input) COLOR0 ... float2 temp (input.Observer.xy input.Observer.w) 0.5 1 half pixel float depth2 tex2D(DepthSampler, temp) float depth input.Observer.z input.Observer.w if (depth lt depth2) discard return c And the ObserverWVP calculated in XNA Matrix ObserverWVP boneTransforms mesh.ParentBone.Index worldMatrix world Matrix.CreateLookAt(pos, pos direction, Vector3.Up) view Camera.Instance.ProjectionMatrix projection Note that the direction vector is not normalized it signifies the entire vector from the source (the character) to the outter edge of the arc. I'm guessing the pixel shader is wrong. But I have no idea how to modify it. Any suggestions? |
12 | Can I generate collision boxes from a model file with BepuPhysics and XNA? I am currently developing a game using BepuPhysics in XNA 4.0, and I am trying to reasonably match the in game collision Entities with the Model they are associated with. My current workflow involves guessing what size the various segments of the model are, guessing a size and position of a box to match each segment, and throwing stuff at it to see if I'm right. This is not an efficient process. Is there a way to automatically generate the Entity from the Model? If not, is there some other way to speed up my workflow? |
12 | How can I track how "well lit" a player is so that I can determine if my AI can see him or her? I want to see how well lit the player character is in an environment so that my AI can react (or not) to the player when he or she is visible. Currently I am doing this by reading back the color data of the final render target and computing the brightness of the player's region. It seems expensive and taxing, so I was wondering if there is a better way to approach this? |
12 | Xna GS 4 Animation Sample bone transforms not copying correctly I have a person model that is animated and a suitcase model that is not. The person can pick up the suitcase and it should move to the location of the hand bone of the person model. Unfortunately the suitcase doesn't follow the animation correctly. it moves with the hand's animation but its position is under the ground and way too far to the right. I haven't scaled any of the models myself. Thank you. The source code (forgive the rough prototype code) Matrix tran new Matrix man.model.Bones.Count The absolute transforms from the animation player man.model.CopyAbsoluteBoneTransformsTo(tran) Vector3 suitcasePos, suitcaseScale, tempSuitcasePos new Vector3() Place holders for the Matrix Decompose Quaternion suitcaseRot new Quaternion() The transformation of the right hand bone is decomposed tran man.model.Bones "HPF RightHand" .Index .Decompose(out suitcaseScale, out suitcaseRot, out tempSuitcasePos) suitcasePos new Vector3() suitcasePos.X tempSuitcasePos.Z The axes are inverted for some reason suitcasePos.Y tempSuitcasePos.Y suitcasePos.Z tempSuitcasePos.X suitcase.Position man.Position suitcasePos The actual Suitcase properties suitcase.Rotation man.Rotation new Vector3(suitcaseRot.X, suitcaseRot.Y, suitcaseRot.Z) I am also copying the bone transforms from the animation player in the Person class like so The transformations from the AnimationPlayer Matrix skinTrans new Matrix model.Bones.Count skinTrans player.GetBoneTransforms() copy each transformation to its corresponding bone for (int i 0 i lt skinTrans.Length i ) model.Bones i .Transform skinTrans i EDIT Unfortunately I can't add screenshots, as this specific project has been lost to time. I still want to know why it didn't work, though. |
12 | XNA 4.0 Problem with loading XML content files I'm new to XNA so hopefully my question isn't too silly. I'm trying to load content data from XML. My XML file is placed in my Content project (the new XNA 4 thing), called "Event1.xml" lt ?xml version "1.0" encoding "utf 8" ? gt lt XnaContent gt lt Asset Type "MyNamespace.Event" gt error on this line lt name gt 1 lt name gt lt Asset gt lt XnaContent gt My "Event" class is placed in my main project using System using System.Collections.Generic using System.Linq using System.Text using System.Xml.Linq namespace MyNamespace public class Event public string name The XML file is being called by my main game class inside the LoadContent() method Event temp Content.Load lt Event gt ("Event1") And this is the error I'm getting There was an error while deserializing intermediate XML. Cannot find type "MyNamespace.Event" I think the problem is because at the time the XML is being evaluated, the Event class has not been established because one file is in my main project while the other is in my Content project (being a XNA 4.0 project and such). I have also tried changing the build action of the xml file from compile to content however the program would then not be able to find the file and would give this other warning Project item 'Event1.xml' was not built with the XNA Framework Content Pipeline. Set its Build Action property to Compile to build it. Any suggestions are appreciated. Thanks. |
12 | Finding a specific point in a graphic model in code I'm not really sure what I'm asking, so sorry for the bad title. I'm still new to game programming and especially the "game specific parts" like models and graphics. Let's say I have a model of a space ship. On this model there's are a couple of locations where I want to place thrusters and there's another spot for a large main thruster. I think I have most of the physics figured out. I can place thrusters at positions relative to the center of mass and the ship behaves appropriately when they're fired. Now, back to the model how do I place my engines (in the simulation), how to get the relative X, Y and Z values from the model? Obviously, the naive solution would be to open up the model in a modelling program and find the coordinate where I want the engines to be placed and then put those values in my database. That would mean that every time I change the model or create a new ship I'd need to redo this procedure and handle a lot of values. Surely this can't be how it's done? Is there a way to "mark" a point in a model and find that point from code? Am I missing something obvious? I'm using C and XNA, by the way. |
12 | Textures do not render on ATI graphics cards? I'm rendering textured quads to an orthographic view in XNA through hardware instancing. On Nvidia graphics cards, this all works, tested on 3 machines. On ATI cards, it doesn't work at all, tested on 2 machines. How come? Culling perhaps? My orthographic view is set up like this Matrix projection Matrix.CreateOrthographicOffCenter(0, graphicsDevice.Viewport.Width, graphicsDevice.Viewport.Height, 0, 0, 1) And my elements are rendered with the Z coordinate 0. Edit I just figured out something weird. If I do not call this spritebatch code above doing my textured quad rendering code, then it won't work on Nvidia cards either. Could that be due to culling information or something like that? Batch.Instance.SpriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone) ... spriteBatch.End() Edit 2 Here's the full code for my instancing call. public void DrawTextures() Batch.Instance.SpriteBatch.Begin(SpriteSortMode.Texture, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone, textureEffect) while (texturesToDraw.Count gt 0) TextureJob texture texturesToDraw.Dequeue() spriteBatch.Draw(texture.Texture, texture.DestinationRectangle, texture.TintingColor) spriteBatch.End() if !NOTEXTUREINSTANCING no work to do if (positionInBufferTextured gt 0) device.BlendState BlendState.Opaque textureEffect.CurrentTechnique textureEffect.Techniques "Technique1" textureEffect.Parameters "Texture" .SetValue(darkTexture) textureEffect.CurrentTechnique.Passes 0 .Apply() if ((textureInstanceBuffer null) (positionInBufferTextured gt textureInstanceBuffer.VertexCount)) if (textureInstanceBuffer ! null) textureInstanceBuffer.Dispose() textureInstanceBuffer new DynamicVertexBuffer(device, texturedInstanceVertexDeclaration, positionInBufferTextured, BufferUsage.WriteOnly) if (positionInBufferTextured gt 0) textureInstanceBuffer.SetData(texturedInstances, 0, positionInBufferTextured, SetDataOptions.Discard) device.Indices textureIndexBuffer device.SetVertexBuffers(textureGeometryBuffer, new VertexBufferBinding(textureInstanceBuffer, 0, 1)) device.DrawInstancedPrimitives(PrimitiveType.TriangleStrip, 0, 0, textureGeometryBuffer.VertexCount, 0, 2, positionInBufferTextured) now that we've drawn, it's ok to reset positionInBuffer back to zero, and write over any vertices that may have been set previously. positionInBufferTextured 0 endif |
12 | Error loading "SpriteFont1". File not found I have an issue while trying to load a font file with the extension ".xnb" and I am receiving following error Error loading "SpriteFont1". File not found. For following code public static Dictionary lt string, T gt LoadListContent lt T gt (this ContentManager contentManager, string contentFolder) DirectoryInfo dir new DirectoryInfo(contentManager.RootDirectory " " contentFolder) if (!dir.Exists) throw new DirectoryNotFoundException() Dictionary lt String, T gt result new Dictionary lt String, T gt () FileInfo files dir.GetFiles(" . ") foreach (FileInfo file in files) string key Path.GetFileNameWithoutExtension(file.Name) result key contentManager.Load lt T gt (key) return result The file is actually there and I am getting here FileInfo files dir.GetFiles(" . ") one file which is present in the folder. I am using the function like this fontList ContentLoader.LoadListContent lt SpriteFont gt (Content, "Fonts") Is there something which I have overlooked? |
12 | Problem with Rotation C XNA I have a projecile(Hook) and the tail of the projectile(yellow balls) TailProjectile class draws a ball at the exact position of the projectile(hook) and let it there until the projectile ends I'd like to draw the ball at the start of the hook(red circle) because by now it draws at the projectile image position(blue point) How can I do it independent of the rotation of the hook? This is how I calculate the rotation of the projectile distanceY endPosition.Y initialPosition.Y distanceX endPosition.X initialPosition.X if (distanceX lt 0) animation.SprtEffects SpriteEffects.FlipVertically animation.Rotation (float)Math.Atan2(distanceY, distanceX) Then I pass the projectile to the tail and draw the ball if (hasTail) tail.Update(gameTime, position , animation.Rotation,animation.SprtEffects) And at the TailProjectile update class public void Update(GameTime gameTime,Vector2 p,float rotation,SpriteEffects sprtEffect) if (Vector2.Distance(animations animations.Count 1 .Position, p) gt distanceBetween) Animation tempAnimation new Animation() tempAnimation.LoadContent(content, image, "", p) tempAnimation.Rotation rotation tempAnimation.SprtEffects sprtEffect tempAnimation.DrawColor color animations.Add(tempAnimation) And the Animation Draw spriteBatch.Draw(image, position origin, sourcRect, drawColor alpha, rotation, origin, scale, sprtEffects, 0.0f) Edit Using rotation matrix solve half of the problem My problem now is how can I calculate it for angles higher than 90 ? (third picture of the image) double xO, yO xO originpoint.X Math.Cos(rotation) originpoint.Y Math.Sin(rotation) yO originpoint.X Math.Sin(rotation) originpoint.Y Math.Cos(rotation) initialAnimation.Position new Vector2((float)xO initialAnimation.Position.X, (float)yO initialAnimation.Position.Y) |
12 | Questions about dynamic loading and unloading of assets and game state I've wondered about this for a while as I worked on my project, but couldn't quite come up with the best way to expose my problem. I'll start with some context. Context I have a game that is divided into rooms. So from an asset point of view, it makes sense to load and unload them on a room by room basis. In my case this boils down to all the textures and audio files required by that room. However, player triggered events can change the state of any dynamic object in the world, even those that are not on the current room. Furthermore, since the game is multiplayer, even if I'm not seeing the changes immediatly, other players might. So, even if the assets aren't loaded, I still need some way to register that change in state. The way I'm currently handling this is to keep the entire game world state in memory since the start of the game, and only bother about dynamically loading and unloading its assets. Which leads to the following questions related to resource management. Questions Loading and storing the entire game state at once seems reasonable for the scope of my games, but I get the feeling it wouldn't scale very well to larger projects. So how is this usually implemented in massive games such as MMOs that need to update a large amount of entities that are far away from the player? Assets that are guaranteed to be needed for a particular room (such as the room's scenario and static objects) can be loaded when the player enters the room possibly with a transition or a loading screen in between. But what about assets for unpredictable game entities that might suddenly come into your current room at any time, such as other players? Would it be reasonable to treat those separately, load them all at once when the game starts, and keep them in memory the entire time, or would it be better to load them and unloaded dynamically in a separate thread? And in that case, does XNA handle loading assets from another thread well? |
12 | Algorithm to find all tiles within a given radius on staggered isometric map Given staggered isometric map and a start tile what would be the best way to get all surrounding tiles within given radius(middle to middle)? I can get all neighbours of a given tile and distance between each of them without any problems but I'm not sure what path to take after that. This feature will be used quite often (along with A ) so I'd like to avoid unecessary calculations. If it makes any difference I'm using XNA and each tile is 64x32 pixels. |
12 | Problem building a color grading map I am trying to build a default color grading map into a 1024x32 RenderTarget. Here is my shader code VertexShaderOutput VertexShaderFunction(VertexShaderInput input) VertexShaderOutput output output.Position float4(input.Position,1) output.TexCoord input.TexCoord return output float4 PixelShaderFunction(float2 TexCoord TEXCOORD0) COLOR0 float temp TexCoord.r 1024 float4 result (float4)0 result.a 1 result.r (temp 32) 32 result.g TexCoord.g result.b TexCoord.r return result I'm using Catalin Zima's quad renderer to render the color grading map AND to render the contents of the texture back onto the screen. Here is the copy shader texture Texture sampler targetSampler sampler state Texture (Texture) AddressU CLAMP AddressV CLAMP MagFilter POINT MinFilter POINT Mipfilter POINT VertexShaderOutput VertexShaderFunction(VertexShaderInput input) VertexShaderOutput output output.Position float4(input.Position,1) output.TexCoord input.TexCoord halfPixel return output float4 PixelShaderFunction(float2 TexCoord TEXCOORD0) COLOR0 return tex2D(targetSampler, TexCoord) When I take the resulting image into the Photoshop, the bottom right pixel of the texture always equals (247, 247, 255), even though top left color equals zero. What could be the problem? I checked the quad renderer class it is recording texture coordinates exactly 0,1 into the quad's corners. I am aligning pixels to texels with the halfPixel and using point texture sampling. Somewhy the V component of texture coordinates never reaches one. I have no clue where the problem can be. As I plan to use this texture for color grading, the accuracy is crucial. UPDATE So far I can only achieve the needed result with the folowing shader code float4 PixelShaderFunction(float2 TexCoord TEXCOORD0) COLOR0 float temp TexCoord.r 1024 float4 result (float4)0 result.a 1 float m (temp 32) result.r m 32 0.035f m 32 result.g TexCoord.g 0.035f TexCoord.g result.b TexCoord.r return result Which is very wierd. UPDATE 2 Ok, I had to modulo divide over 33 instead of 32, but I still have to correct the V coordinate. float4 PixelShaderFunction(float2 TexCoord TEXCOORD0) COLOR0 float temp TexCoord.r 1024 float4 result (float4)0 result.a 1 float m (temp 33) result.r m 33 0.035f m 33 result.g TexCoord.g 0.035f TexCoord.g result.b TexCoord.r return result |
12 | Drawing Farseer Fixtures Is there any way how to draw a Polygon Fixture from Farseer Physics with XNA? As I deform these polygons at runtime I can't take any texture from my Content folder, the texture must be generated at runtime too. |
12 | Run XNA game without graphics Wondering if there is anyway to run an XNA game with out displaying anything. I have a working game that runs in a client server setup where one player is the host and other people can connect to his game. I now want to be able to run the game as a host on a decicated server with no graphics card, basically I dont want to run any Draw() logic at all. Do i really need to go through the entire game and remove all references to XNA? How have people done this? EDIT The reason I want to do this is because I have a working client server setup in the game and I dont want to make a separate "headless" server program. |
12 | Spritesheet filesize gets huge after compiling I have a 14x2 spritesheet which has 125 Kb in raw .png. But as soon as I compile that to .xnb, it mutates to 4 MB. So my question is Why is that? And how can I fix that? |
12 | 3d world vertex translation to go to 2d screen coords My technical english is a little rusty so to avoid misunderstands please be patient with me ) I will try to be brief and clear Situation I have a 2d sprite character on the screen I've just start learning how to draw 3d primitives and work with the cameras I'm working on a 2d isometric environment I made a 3d isometric triangle which I want to center in character I'm trying to do something similar to a flashlight Problem The triangle is not centered on character (probably because of the scales between 2d and 3d workspace) the triangle speed does not match the character speed. Code player vision playerVision new VertexPositionColor 3 playerVision 0 .Position new Vector3( 15f, 30f, 0f) playerVision 0 .Color Color.Transparent playerVision 1 .Position new Vector3(0f, 0f, 0f) playerVision 1 .Color new Color(70, 102, 25, 20) playerVision 2 .Position new Vector3(15f, 30f, 0f) playerVision 2 .Color Color.Transparent private void SetUpCamera() isometric angle is 35 , for 50y 107z viewMatrix Matrix.CreateLookAt(new Vector3(0, 107, 50), new Vector3(0, 0, 0), new Vector3(0, 1, 0)) TODO use viewport for whole window or just the draw area ? projectionMatrix Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, GameInterface.vpWholeWindow.AspectRatio, 1.0f, 300.0f) private void drawPlayerVision(GameTime gameTime, SpriteBatch spriteBatch, Vector2 playerDrawPos) 50 is related with the camera position in the axis TODO this probably is incorrect since it should be a module of the distance? btw points Vector2 playerPos playerDrawPos 50 effect.CurrentTechnique effect.Techniques "ColoredNoShading" effect.Parameters "xView" .SetValue(viewMatrix) effect.Parameters "xProjection" .SetValue(projectionMatrix) rotating like a radar Matrix worldMatrix Matrix.CreateRotationZ(3 visionAngle) moving to the character worldMatrix Matrix.CreateTranslation(new Vector3(playerPos.X, playerPos.Y, 0)) effect.Parameters "xWorld" .SetValue(worldMatrix) effect.Parameters "xWorld" .SetValue(Matrix.Identity) foreach (EffectPass pass in effect.CurrentTechnique.Passes) pass.Apply() Game.GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, playerVision, 0, 1, VertexPositionColor.VertexDeclaration) if you need more details please ask me I've been trying to figure out all by myself so its a little hard for me ) Thank you for your assistance |
12 | Udp VS Tcp connection for a platformer multiplayer Tcp is connection based so it's really good for chat or login or anything that needs reliability. Udp should be used for lots of small packets like position packets... The problem is that in a game like what I'm doing right now (terraria like), I can't decide what to use and how to use it properly. I though about using both at the same time, but can't find a way to ensure the udp "connection" will work. If I were to choose UDP, is there a way I could make a "connection" out of it? to rely on it for login or chat messages? And if I were to use TCP, would there be a way to speed it up? More info I'm doing this in C .NET with XNA (I know it's no longer developped but I like it P). I would also like to use Serialized objects (.Net BinaryFormatter), but it uses streams, and stream are only available in TCP... which makes it more attractive... Thanks a lot! |
12 | XNA 3d model mesh.draw() throws TextureCoordinate0 is missing error I've downloaded a bunch of 3d models from turbosquid.com. The majority of the one's I've downloaded are simply .fbx files. When I load the model into my game and run it, the following error is thrown in mesh.draw() An unhandled exception of type 'System.InvalidOperationException' occurred in Microsoft.Xna.Framework.Graphics.dll Additional information The current vertex declaration does not include all the elements required by the current vertex shader. TextureCoordinate0 is missing. All the answers I've found online seem to tell people to reexport the model, or change something in the shader. I don't have access to these, just the fbx file. What can I do? |
12 | Setting Krypton Light to Screen Pixels So a few days back, I started playing around with Krypton XNA for 2D lighting in my game. I noticed in general, that spawning a light at (0,0) with Krypton causes the light to appear in, pretty much, the centre of the game screen. Is there any way to change this so a Krypton light's "starting point" at 0,0 would spawn at the top left of the screen, and thus follow the standard screen co ordinates for position? I ask because currently I'm busy working on my game where my spawn point is 512,512 . With hard code, the closest I've got to the light being "central" to this point is the vector position 12, 20 , which makes no sense and is impossible to craft, mathematically, if I want the light to move with the camera (the position 480,512 maps roughly to 10, 20 ). So, is there any way to "normalise" the krypton lights to use standard screen co ordinates? If you guys can, play around with the demo from the site and please see if you can find anything out about it. Documentation on the engine is rather scarce, so it's difficult to find anything relevant to my "pixel perfect" need. It might just also be something in the code with regards to the matrices that I'm not fully understanding. Any help would be useful. Thanks. |
12 | Retrieving model position after applying modeltransforms in XNA For this method that the goingBeyond XNA tutorial provides, it would be really convenient if I could retrieve the new position of the model after I apply all the transforms to the mesh. I have edited the method a little for what I need. Does anyone know a way I can do this? public void DrawModel( Camera camera ) Matrix scaleY Matrix.CreateScale(new Vector3(1, 2, 1)) Matrix temp Matrix.CreateScale(100f) scaleY rotationMatrix translationMatrix Matrix.CreateRotationY(MathHelper.Pi 6) translationMatrix2 Matrix modelTransforms new Matrix model.Bones.Count model.CopyAbsoluteBoneTransformsTo(modelTransforms) if (camera.getDistanceFromPlayer(position position1) gt 3000) return foreach (ModelMesh mesh in model.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.EnableDefaultLighting() effect.World modelTransforms mesh.ParentBone.Index temp worldMatrix effect.View camera.viewMatrix effect.Projection camera.projectionMatrix mesh.Draw() |
12 | Is using XNA title storage for level config files a Bad Idea? I've reached the point in development where my Game Engine can actually do stuff, and it's time to start thinking about how to store load the various bits and pieces where they need to be. I've decided to go with file storage (rather than a database), which means I'm probably going to be using .xml, .json, or .csv files. The only remaining question is how to actually store them within the game's binaries (so that any players won't be able to edit levels willy nilly). XNA's Title Storage, being read only, seemed as good a starting place as any, but when I loaded up the MSDN page, there's this warning on the top This topic describes how to add files to title storage that the game will access through stream I O. This is the exceptional case, and is not recommended for most XNA Game Studio games. Instead, consider using the Content Pipeline to manage your game data most efficiently. Emphasis mine. So is it a bad idea to use Title Storage for level config files, or is that warning intended to stop people from using it to store things like Texture2Ds and SpriteFonts ? |
12 | Non rectangular hitbox methods in XNA I'm creating a 2D top down RPG, and many of my buildings scenery have non rectangular corners to the textures. Does anyone know a good way to create circular triangular polygonal hitboxes, or is too intensive too be worth it? P.S. If it is too intensive, I can stick with rectangular hitboxes, no big deal. |
12 | Am I hurting myself by not knowing C for game design? Right now, I feel I am strong in both Java a C . (Not much of a leap from one to the other really). While I don't expect a game designer programmer is an attainable goal early on in my career, This is a goal I will reach later on in my career. With this in mind, I feel that ignoring C and game design tools associated with it are eventually going to hurt me or slow me down in my ability to reach my goal. Is this the case? Or can I continue to hone my C skills using XNA and WPF for personal projects that can elevate me into such a career? |
12 | How do I get the mouse position relative to the window, not the whole screen? I am developing an XNA game. I run it in window mode. I need to handle mouse events, but when I use the Mouse class from Xna.Framework.Input.Mouse, I get the the mouse position on the whole screen. I use this code MouseState state Mouse.getState() Point position new Point(state.X,state.Y) Rectangle hitbox new Rectangle(180, 410, 14, 14) if (area.Contains(mousePosition)) fire event How do I detect the mouse position within the current game window? |
12 | Monogame XNA Making animations play once per click I'm currently making a gbjam entry and everything has been going smoothly up to this point. My issue being that I've implemented a shooting mechanic and along with it an animation to play as a shot is fired, however I'm struggling to make it so that the animation plays properly each click of the mouse. I only ever see sporadic flickers with no real pattern to them. I'm using an animation class and for anything else it's been working fine. Here's my animation's Draw() method public void Draw(SpriteBatch sB, GameTime gT, Vector2 pos) time (float)gT.ElapsedGameTime.TotalSeconds while (time gt frameTime) frameIndex time 0f if (frameIndex gt totalFrames) frameIndex 0 Rectangle source new Rectangle(frameIndex frameWidth, 0, frameWidth, frameHeight) sB.Draw(spriteSheet, pos, source, Color.White, 0.0f, origin, 1.0f, SpriteEffects.None, 0.0f) For reference the animation spritesheet is 20 frames long, each 128px by 128px. Here is the Update() and Draw() calls that are use in handling shooting and the shooting animation region Shooting if (mS.LeftButton ButtonState.Pressed amp amp mSP.LeftButton ButtonState.Released) if (bCount gt 0) shooting true bCount Debug.WriteLine("Bang!" " Rounds Left " bCount) else shooting false Debug.WriteLine("OUT OF AMMO") else shooting false if (mS.RightButton ButtonState.Pressed amp amp bCount 0) shooting false bCount 6 Debug.WriteLine("RELOAD") endregion mSP mS mSP being the previous mouse state and mS being the current public void Draw(SpriteBatch sB, GameTime gT, Camera cam) if (shooting) revolverShoot.Draw(sB, gT, fpsPos) else revolverIdle.Draw(sB, gT, fpsPos) If anyone could offer any ideas as to 'force' the game to complete the animation first before continuing I would be really greatful. |
12 | Rotation before scaling image Lower resolution rotation? (XNA C ) Currently, when I rotate the image using SpriteBatch.Draw() the image is rotated after it is scaled. Resulting in Which is using the code public override void Draw(GameTime gameTime) sprite batch.Draw( texture, parent.position, new Rectangle(0, 0, (int) 25, (int) 25), Color.White, rotation, new Vector2(texture.Width 2, texture.Height 2), new Vector2(2, 2), SpriteEffects.None, 0f) However what I would like to see is more on the grounds of I've tried to directly edit the texture itself instead of rotating using spritebatch, only I have found that it was incredibly inefficient. Edit 1 I am currently looking around at RenderTarget2D and such. Possible solution to my problem. |
12 | Using an object as a model to avoid too many parameters XNA C I have 3 classes(Skill,Projectile and Status),Skill has Projectile and Projectile has Status, all of them need to read information from a txt and to avoid open it everytime I want to create an object I want to read all the txt on Skill and pass the information Projectile need as arguments and then on Projectile create Status passing the information needed as arguments too As Projectile going to create a lot of Status objects it need to receive Projectile's informations and Status's informations from Skill, to avoid too many parameters can I create a Status object on Skill and pass it to Projectile and everytime I need to create another status I use the first one as a model? As example public class Skill String skillName,projectileName,statusName int skillNumber,projectileNumber,statusNumber public Skill() Code to read txt and fill variables What is happening Projectile projec new Projectile(projectileName,statusName,projectileNumber,statusNumber) To avoid above Status status new Status(statusName,statusNumber) Projectile projec new Projectile(projectileName,projectileNumber,status) And then at Projectile public class Projectile Constructor,variables and methods Method that create Status public void Update() if(hitEntity) this status was received from Skills Status tempStatus new Status(status.statusName,status.statusNumber) |
12 | Drawing Farseer Fixtures Is there any way how to draw a Polygon Fixture from Farseer Physics with XNA? As I deform these polygons at runtime I can't take any texture from my Content folder, the texture must be generated at runtime too. |
12 | (XNA) Checking coordinates, directly vs List vs Dictionary I'm currently working on a generator that generates rooms in biomes and i was wondering what is the fastest way of checking if a certain position is already occupied. I've got 3 possible ways of doing this 1. Use nested foreach loops to directly loop through all rooms and check the position. (ugh) public bool IsOccupiedPosition(Vector2 position) foreach (Biome biome in this.Biomes) foreach (Room room in biome.Rooms) if (room.Position position) return true return false 2. Use a List, put everything in there, then check that using the Contains() method. public List lt Vector2 gt RoomCoordinatesAsList get set public void AddRoomCoordinates(Vector2 position) this.RoomCoordinatesAsList.Add(position) public bool IsOccupiedPosition(Vector2 position) return this.RoomCoordinatesAsList.Contains(position) 3. Use a Dictionary, where the first type is the X position and the second a list of Y positions. (my preference) public Dictionary lt float, List lt float gt gt RoomCoordinates get set public void AddRoomCoordinates(Vector2 position) if (!this.RoomCoordinates.ContainsKey(position.X)) this.RoomCoordinates.Add(position.X, new List lt float gt ()) this.RoomCoordinates position.X .Add(position.Y) public bool IsOccupiedPosition(Vector2 position) return (this.RoomCoordinates.ContainsKey(position.X) amp amp this.RoomCoordinates position.X .Contains(position.Y)) |
12 | Port a WP7 game to WP8 with Monogame I have a full working game for WP7, I want to port it to WP8 with Monogame. I have installed Monogame and I have done all tests to see that it is working inside Visual Studio Express 2012 for Windows Phone 8. Now I just don't understand how to rebuild my WP7 version game within a Monogame project to target WP8 devices. So, if you would have the entire solution of a WP7 game, how would you make it work on WP8 with Monogame? Thanks! |
12 | What do I need to do to my slope collision detection to prevent the player from passing through my collision? I've recently implemented slope collision detection for my project. The issue I'm having is that the character occasionally passes through the line. This usually occurs when the characters MoveAcceleration is increased from 5000 to 8000 via a game mechanic. I was wondering if there is a way to make the line collision more reliable without reducing the MoveAcceleration variable ? This is how the characters position is calculated velocity.X movement MoveAcceleration elapsed Position velocity elapsed This is how the slopeCollision is handled private void HandleSlopeCollisions(GameTime gameTime) isOnSlope false float elapsed (float)gameTime.ElapsedGameTime.TotalSeconds if (velocity.Y gt 0) if (attachedPath ! null) isOnSlope true position.Y attachedPath.InterpolateY(position.X) velocity.Y 0 if (position.X lt attachedPath.MinimumX position.X gt attachedPath.MaximumX) attachedPath null else Vector2 footPosition position Vector2 expectedFootPosition footPosition velocity elapsed CollisionPath landablePath null float landablePosition float.MaxValue foreach (CollisionPath path in collisionPaths) if (expectedFootPosition.X gt path.MinimumX amp amp expectedFootPosition.X lt path.MaximumX) float pathOldY path.InterpolateY(footPosition.X) float pathNewY path.InterpolateY(expectedFootPosition.X) if (footPosition.Y lt pathOldY amp amp expectedFootPosition.Y gt pathNewY amp amp pathNewY lt landablePosition) isOnSlope true landablePath path landablePosition pathNewY if (landablePath ! null) isOnSlope true velocity.Y 0 footPosition.Y landablePosition attachedPath landablePath position.Y footPosition.Y else attachedPath null |
12 | Farseer Physics Ways to create a Body? I want to create something similar to this using farsser and Kinect https vimeo.com 33500649 This is my implementation until now http www.youtube.com watch?v GlIvJRhco4U I have the outline vertices and the triangulation of the user. And following the Texture to Polygonmsample i used this line to create the shape, where farseerObject is a list of vertices of the triangles compound BodyFactory.CreateCompoundPolygon(World, farseerObject, 1f, BodyType.Dynamic) But I have to update the body each frame (like 30 fps) and this is very slow. I get just 2 or 3 fps. There's another (faster) way to create the Body from a list of triangles or the contour vertices? How do you think they do this on Box2D? Update After some testings i used EdgeShapes for the user contour (without triangulation) and i update the vertices for that edges in the fixtures every frame, now all is faster. ((EdgeShape)(farseerBody.FixtureList i .Shape)).Vertex1 new Vector2(farseerVertices i .X, farseerVertices i .Y) But the collisions does not work! My approach is incorrect? |
12 | Is it OK to release the source code for your own Xbox Live indie game? Between not being sure how to phrase my question for Google and not being a lawyer, I thought it might be easier to ask you guys. Specifically, I want to know if it's OK to sell an Xbox Live indie game while simultaneously distributing the source code and other assets via GitHub or something. Edit The Communist Duck asked "why not?" One reason I can think of is that Microsoft has a small stake in a game's sales. They are hosting the demo full game, they might be dedicating an advertising slot to the game in their "latest" section, etc. It's true they get a cut of each sale, but they get nothing if everyone just goes and downloads the free version. Anyway, it's not a matter of what is reasonable and logical, it's a matter of what the terms and conditions allow. I'm going to read through them regardless, but I was hoping someone already knew. |
12 | Kinect Hand tracking in xna I'm trying to create an application using the Kinect to simulate the following project Kinect Hand Tracking I want my project to have similar usability with the Kinect tracking hand and finger positions for use in a menu system, or to navigate another system. What I would like to know is is it possible for the exact same to be accomplished in XNA using Kinect? I know that it can be done in Winform C , but I know XNA C a lot better and would (ideally) prefer to use that. |
12 | Ideas wich design patterns apply in my school assignment For a assignment for school i've to develop a game in Microsoft XNA 4. Let me first clear out that my intention of this post is NOT to give me codes. I want to figure out things by my self. The intention of this post is to help me and give me advice wich design patterns may be better to apply in wich situation. This game should use the following design patterns strategy factory decorator singleton observer template The assignment is as follow In this game the player should avoid the attack from his enemies who want to attack his spaceship. The enemies have their own way of attack and movement. When the game starts the player has one cannon who can shoot bullets each 0.2 seconds. The spaceship can move horizantally with the keyboard. With the spacebar the player kan shoots bullets. There are 3 kind of enemies who have their own attack and the way they move. Chure Moves horizantally from left to right, each time when the chure hits the edge he moves down and again he move horizontally but this time in the opposite direction (thus from right to left). Each chure drops at any time (random) a bomb. Each level the speed of the drop will increase. Thege Moves from the corner of the stage diagonal to the player. When the Thege hits the player, the player loose one life and starts the level again. When the Thege don't hit the player and reach the bottom of the stage he will remove from the stage and won't come back again in that level. Sinode Moves from top to bottom of the stage, when the Sinode reach the bottom of the stage hi moves the opposite direction (from bottom to top). The Sinode stays on the stage as long as the player didn't shoot him. When the player shoots the Sinode he will be remove from the stage. Each enemie can carry an upgrade wich will be released when he will be shot by the player. either the enemie has a upgrade or not has been choosen randomly. There are three kinds of upgrades. The player can use his spaceship but once expand with each type of upgrade. If the player already has a upgrade the upgrade will remove from the stage. The three type of upgrades are Lasers (Specs aren't important) Rockets (Specs aren't important) Guided missile (Specs aren't important) some conditions to the game The game consists of 3 levels Each player starts with 3 life The level will be ended when all of the enemies are destroyed or not visible on the stage. Now i've some ideas wich design pattern will be good by wich scenario but i would be gratefull if u guys can help me out how i can implement the factory and the observer pattern in this case and maybe help me out and give advice how i can implement the rest of the patterns. Thank u |
12 | string and int concatenation resulting in null for a Tetris clone? I'm writing a tetris clone, and I have sprites (of every possible piece and rotation) loaded through the XNA content pipeline. For example, I have assets "i", "i2", "i3", and "i4" for each rotation of the 4 block long I tetrimino. For the O tetrimino, I only have asset "o", because the O tetrimino doesn't require any rotations. I want to load each of these assets into a 2D array of Texture2Ds. Here's my attempt 1 Texture2D , tetriminoTextures new Texture2D 7, 4 2 char tetriminos 'o', 'i', 'l', 'j', 'z', 's', 't' 3 string t 4 5 for (int i 0 i lt 7 i ) 6 7 for (int j 1 i lt 4 i ) 8 9 if (i 0 j 1) If char i 'o', then don't consider rotations. 10 The square piece doesn't have rotations. 11 If j 1, then leave the asset name as is. 12 t letters i .ToString() 13 else (i ! 0 amp amp j lt 2 amp amp j lt 4) 14 t letters i .ToString() j 15 tetriminoTextures i, j 1 Content.Load lt Texture2D gt (t) 16 17 However, when I attempt to spriteBatch.Draw(tetriminoTextures x, y , some position vector , Color.White) I get an ArgumentNullException. Apparently tetriminoTextures x, y is null when y gt 1 amp amp y lt 3. I have no idea what's going on. I think it may have something to do with my concatenating a string and an int together in line 14. But I'm getting an ArgumentNullException even when i 0 amp amp j gt 2 amp amp j lt 4 (i.e. for each rotation of the O tetrimino excluding the first one), though the if statement in line 9 should have caught these cases. Any help would be appreciated! |
12 | Child parent rendering (flash) in XNA i am currently in the process of implementing a render engine that works like flash's. Where a sprite is drawn inside another sprite and reflects all transformation (rotation, scale, etc) on the parent. I have my transformation setup like so. public Matrix transform get Matrix m transform Matrix.CreateTranslation(new Vector3(x, y, z)) Matrix.CreateRotationZ(rotation) Matrix.CreateScale(scale) return m transform But i cannot use spritebatch to render the sprite with a matrix. Is there a way to properly do this ? Thanks alot ) |
12 | XNA significant loss in fps by just adding a few hundred thousand more triangles? I've got a minecraftish game that's running nice and smooth with a total of 9.3 million triangles, about 50 70fps average. Then if I try to render 9.9 million triangles I get hell and it drops to lt 1 fps. I'm drawing them exactly the same way, it's definitely the drawing as I have a vertex buffer for each chunk, then I run through them all, check if they're in sight and if they are I draw them. It works fine at high fps until I have just those few extra triangles which destroy the FPS. Edit Added drawing code First I loop through all the chunks. I check if they're visible and if they are I mark them as visible then draw them. foreach (Chunk chunk in GlobalWorld.LoadedChunks) if (chunk null !chunk.DrawThis) continue if (!player.ViewFrustrum.Intersects(chunk.Bounding)) chunk.IsInSight false continue chunk.IsInSight true GlobalGame.graphicsDevice.SetVertexBuffer(chunk.VertexBuffer) GlobalGame.graphicsDevice.Indices chunk.IndexBuffer ChunkShader.Parameters "xWorld" .SetValue(chunk.WorldMatrix) ChunkShader.CurrentTechnique.Passes 0 .Apply() GlobalGame.graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, chunk.VertexBuffer.VertexCount, 0, chunk.IndexBuffer.IndexCount 3) Then after that I draw all the transparent parts of the chunk (so they don't conflict with other chunks). I already made clear if they're visible above so I just check if that bool is true. foreach (Chunk chunk in GlobalWorld.LoadedChunks) if (chunk null !chunk.IsInSight !chunk.DrawThisTransparent) continue GlobalGame.graphicsDevice.SetVertexBuffer(chunk.TransparentVertexBuffer) GlobalGame.graphicsDevice.Indices chunk.TransparentIndexBuffer ChunkTransparencyShader.Parameters "xWorld" .SetValue(chunk.WorldMatrix) ChunkTransparencyShader.CurrentTechnique.Passes 0 .Apply() GlobalGame.graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, chunk.TransparentVertexBuffer.VertexCount, 0, chunk.TransparentIndexBuffer.IndexCount 3) With 3721 chunks loaded it runs fine with them all being drawn at the same time. With 3844 chunks being loaded it runs fine unless you view all of them. Now that's only just over 100 more chunks yet it's dropping from 60fps to lt 1 fps. |
12 | Rotate model using quaternion Currently I have this to rotate my 3D model that rotates on it's local axis independent from the world's axis Rotate model with Right Thumbstick modelRotation pController.ThumbSticks.Right.X mRotSpeed float value What I'm trying to do is rotate the model using quaternion and not by a matrix. I've searched for tutorials, but have found none that explains thoroughly on how to achieve this. Does anyone know how to I can use quaternions to rotate my model or a complete tutorial? |
12 | ResourceContentManager with folders I am attempting to do something like the following http blogs.msdn.com b shawnhar archive 2007 06 12 embedding content as resources.aspx (Access the content via a DLL) However, I need to maintain the folder structure of the fonts and images. I have attempted to add the folders to the resources file, but it doesn't add the folder if I drop it in the resources file in VS. I am thinking I might need to embed the content as just a regular folder, and each file will need its property to be set to embedded resource, but I need to use it in another assembly. I looked at http zacharysnow.net 2010 07 03 xna load texture2d from embedded resource but I think I can only do that with textures. I need to do it with fonts as well. I looked at https stackoverflow.com questions 859699 how to add resources in separate folders and that doesn't seem to help me much. Whats the best way I can embed my resources in another assembly, while maintaining my content loading strings? |
12 | Displaying text letter by letter I am planing to Write a Text adventure and I don't know how to make the text draw letter by letter in any other way than changing the variable from h to he to hel to hell to hello That would be a terrible amount of work since there are tons of dialogue. Here is the source code so far protected override void Update(GameTime gameTime) input code removed for clarity if (Dialogue 1) Row1 "Input Text 1 Here." Row2 "Input Text 2 Here." Row3 "Input Text 3 Here." Row4 "Input Text 4 Here." if (Dialogue 2) Row1 "Text 1" Row2 "Text 2" Row3 "Text 3" Row4 "Text 4" base.Update(gameTime) protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.CornflowerBlue) spriteBatch.Begin() spriteBatch.Draw(sampleBG, new Rectangle(0, 0, 800, 600), Color.White) spriteBatch.Draw(TextBG, new Rectangle(0, 400, 800, 200), Color.White) spriteBatch.DrawString(defaultfont, Row1, new Vector2(10, (textheight (rowspace 0))), Color.Black) spriteBatch.DrawString(defaultfont, Row2, new Vector2(10, (textheight (rowspace 1))), Color.Black) spriteBatch.DrawString(defaultfont, Row3, new Vector2(10, (textheight (rowspace 2))), Color.Black) spriteBatch.DrawString(defaultfont, Row4, new Vector2(10, (textheight (rowspace 3))), Color.Black) spriteBatch.End() base.Draw(gameTime) |
12 | (XNA) What's a Good Database Program for a Turn Based RPG? I'll begin by saying that I feel my level of expertise matters here, and so I have about a year worth of experience as a programmer in the C language and most of the .NET framework as a whole, but have scarcely worked with databases at all throughout my career so far. Can't exactly say why. Either way, I'm a bit of a beginner, although SQL LINQ I am capable of working with once I have this question resolved. Moving on... At home, I am developing a single player (so only one person needs to access it) turn based RPG in XNA. I have a lot of the logic done and the time has come for me to begin building a database for it. THE REQUIREMENTS There will be both dynamically written data not included with the program (such as the location in the world at which a player saved his game, that he may load in the same place) and read data that needs to be capable of being distributed easily with the program (such as a table containing stats of every monster). THE DESIRED BUT OPTIONAL PERKS Beyond these absolute requirements, ease of use is a second priority I want to focus on. My amatuer nature doesn't want me digging around on ground I am too unfamiliar with. MY ATTEMPTS AT RESEARCH I understand Access to be a simple to use (though oft frowned upon) choice that could work based on needing only one user to access the database at a time. SQL Server could also work, but I understand it to be more difficult to use based on my needs. And in both cases, I am not sure if there are complications associated with the distrubution of pre loaded data with the programs. In this case, I think I should use an XML file to hold the data I want the game to come with, but I am not sure. Amidst all of this, I have also considered creating the .dbml right there in Visual Studio because it seems the simplest, but same issue I don't know the limitations of capability and distribution. I have tried to outline what I know and what I need to accomplish, as well as some of the options I have attempted to research, but ultimately, my knowledge has holes in it I can't find the answers to and I can't form a conclusive answer. Thus, I ask you kind people, based on the above, what is my best option for how to start building my game's database? |
12 | A pattern for a contextual InputState in a Game State Management architecture Context of the question When developing a game using Game State Management I came across a problematic when it came to handling user input I want my game to retrieve user input a single way, but to handle it in a completely different way, depending on the context. For example, the Up key will always mean "Menu Up" when you're in a menu, but if you're in the game, it might do different things, depending on the key bindings. Another difference would be, for example, that in a menu, a .5sec KeyDown on a key should be interpreted as a single command, but when you're in game, a .5sec KeyDown should often be seen as a .5sec movement burst charge shot etc... Then way I though about to achieve this result is the following Have an InputState class that keeps the current and previous Keyboard Gamepad input states, just like the usual InputState class. Have this InputState class implement all the methods I would need in all the different contexts. Create an Interface per context. For example, IMenuInputState, IGameInputState, ICutsceneInputState, etc. These interfaces would only contain the method definitions related to the context. Have the InputState implement all the I ... InputState interfaces. If two or more context need the same method, the same implementation would be used. In the ScreenManager's Update method, the InputState would be Updated, but depending on which screen must handle the InputState, a different I ... InputState would be sent. Even though the screen could access the other methods by casting the interface, only the contextual methods would directly be usable. My question is the following Is my idea a proper common way of handling this issue? If it is, could you tell me the name of that "pattern" or direct me to some online resources so I can read on that and avoid the known pitfalls. If it's not, how would you suggest I handle the problem? Note I know this question is borderline since the answer is partially subjective but I'd appreciate some help on this issue since I think it's a critical decision in my project. |
12 | Downsides of using this integration formula for movement? So I read that Gaffron integration basics tutorial and noticed how the Euler integration method gives a small error over time. I implemented the RK4 and noticed that with constant acceleration, I could simplify the formula. Over the course of an hour with some use of wolframalpha, I noticed that the formula eventually just simplifies down to just this float dt (float)gameTime.ElapsedGameTime.TotalSeconds Position (0.5f Acceleration dt Velocity) dt Velocity Acceleration dt I ran it through a console and sure enough, it gives the proper values for each timestep and the correct final value. Will this formula always yield perfectly accurate answers? My acceleration will always be constant. Is there a name for this formula? |
12 | Drawing with SpriteBatch and GraphicsDevice.DrawPrimitives I've faced with a problem when i tried to draw 2d game with SpriteBatch and GraphicsDevice.DrawUserPrimitives. I suppose that what is drawing with SpriteBatch has higher priority, because i can not see a result of its rendering. GraphiscDevice.DrawUserPrimitives renders only if i comment a line of rendering background. Here is my method Draw. Could you check the order of rendering. What is the reason? protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.BlanchedAlmond) basicEffect.CurrentTechnique.Passes 0 .Apply() spriteBatch.Begin() spriteBatch.Draw(background, new Rectangle X 0, Y 0, Height Bounds.Height, Width Bounds.Width , Color.White) DrawCell() spriteBatch.DrawString(defaultFont, "fps " FPS, new Vector2(10, 75), Color.DarkBlue) spriteBatch.End() base.Draw(gameTime) private void DrawCell() basicEffect.Texture cellBody graphics.GraphicsDevice.DrawUserPrimitives lt VertexPositionTexture gt (PrimitiveType.TriangleList, cell.Triangles, 0, cell.Triangles.Length 3) protected override void Initialize() basicEffect new BasicEffect(graphics.GraphicsDevice) basicEffect.TextureEnabled true basicEffect.Texture bg menu basicEffect.World Matrix.Identity basicEffect.Projection Matrix.CreateOrthographicOffCenter (0, graphics.GraphicsDevice.Viewport.Width, graphics.GraphicsDevice.Viewport.Height, 0, 0, 1) ... |
12 | AABB SAT code detects collision wrongly I've been having trouble getting my SAT code working using AABBs, and I've been trying to find a solution but, I'm scratching my head. For some reason, it detects collisions very wrongly, as shown by this desk check I did. (AABBvsAABB method at bottom.) Consider two AABB, A and B. A X 0, Y 0, W 102, H 19 B X 87, Y 6, W 1, H 1 These are colliding. First, calculate normal Normal (0,0) (87,6) ( 87, 6) Next, we get half widths aExtent 102 2 51 bExtent 1 2 .5 Now lets calculate the overlap of the two. xExtent 51 .5 87 51.5 87 35.5 xExtent is less than zero so it says its not colliding, obviously this is wrong. lt summary gt Compares bounding boxes using Seperating Axis Thereom. lt summary gt public static bool AABBvsAABB(AABB a, AABB b, ref Manifold manifold) manifold.Normal a.Position b.Position Calculate half widths float aExtent a.Width 2f float bExtent b.Width 2f Calculate the overlap. float xExtent aExtent bExtent Math.Abs(manifold.Normal.X) If the overlap is greater than 0 if (xExtent gt 0) Calculate half widths aExtent a.Height 2f bExtent b.Height 2f Calculate overlap float yExtent aExtent bExtent Math.Abs(manifold.Normal.Y) if (yExtent gt 0) Variable to multiply the normal by to make the collision resolve Vector2 faceNormal Check to see which axis has the biggest "penetration" D Collision is happening on Y axis if (xExtent gt yExtent) faceNormal manifold.Normal.X lt 0 ? Vector2.UnitX Vector2.UnitX manifold.PenetrationDepth xExtent manifold.Normal Physics.GetNormal(a.Position, b.Position) manifold.Normal.X faceNormal.X Collision happening on X axis else faceNormal manifold.Normal.Y lt 0 ? Vector2.UnitY Vector2.UnitY manifold.PenetrationDepth yExtent manifold.Normal Physics.GetNormal(a.Position, b.Position) manifold.Normal.Y faceNormal.Y manifold.AreColliding true return manifold.AreColliding Any idea what I am doing wrong here? |
12 | C xna to monogame I'm thinking of going back to xna and c because I have used java 2d, slick 2d and some other libraries. I started off with xna and c but ignored it for java. I'm thinking of going back, but I see xna isn't being developed anymore. I read there is away to convert it to monogame but seems very complicated. XNA look fairly easy, yet I havn't toyed with monogame yet. So what I want to know , is monogame related to xna or close in coding? Would it be easy to understand if you're good with xna? |
12 | Alternative to soundeffect.play()? I have been using a profiler to optimize my game for the Xbox, my aim is as with any optimization to reduce excess CPU and memory usage. I have managed to cut down a lot of the processor time and memory used by my game. However i have a lot of bullets in my game that the player fires and every time a bullet impacts with something the soundeffect.play() method is called to play the explosion. I would like to know if there is a more efficient way of playing the explosion soundeffect? |
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 | Xna custom mouse not allowing me to move its sprite past certain bounds I have written a Custom mouse, with a Custom sprite, using MouseState, and getting the X and Y variables. However i also have a camera that i wrote, and this allows me to leave the initial box. One sprite that can freely move this area, but my mouse gets stuck in a box that seems proportional to my screen resolution some times. This is where i create the Texture, Vector and MouseState of the Custom Cursor Texture2D Mouse texture MouseState mouse state Vector2 Mouse pos This is my Resolution and i have IsFullScreen true graphics.PreferredBackBufferWidth 1600 graphics.PreferredBackBufferHeight 900 Loading the Texture Mouse texture Content.Load lt Texture2D gt ("mouse") Getting the current mouse State this is in the update function mouse state Mouse.GetState() How i set the mouse position Simple Vector2 stuff and i never do anything else to handle the the position of the mouse Mouse pos new Vector2(mouse state.X, mouse state.Y) and this is me Drawing it spriteBatch.Draw(Mouse texture, Mouse pos, Color.White) If you need any more code let me know |
12 | Outline Shader Effect for Orthogonal Geometry in XNA I just recently started learning the art of shading, but I can't give an outline width to 2D, concave geometry when restrained to a single vertex pixel shader technique (thanks to XNA). the shape I need to give an outline to has smooth, per vertex coloring, as well as opacity. The outline, which has smooth, per vertex coloring, variable width, and opacity cannot interfere with the original shape's colors. A pixel depth border detection algorithm won't work because pixel depth isn't a 3.0 semantic. expanding geometry redrawing won't work because it interferes with the original shape's colors. I'm wondering if I can do something with the stencil depth buffer outside of the shader functions since I have access to that through the graphics device. But I don't believe I'm able to manipulate actual values. How might I do this? |
12 | Orienting a model to face a target I have two objects (target and player), both have Position (Vector3) and Rotation (Quaternion). I want the target to rotate and be facing right at the player. The target, when it shoots something should shoot right at the player. I've seen plenty of examples of slerping to the player, but I don't want incremental rotation, well, I suppose that would be ok as long as I can make the slerp be 100 , and as long as it actually worked. FYI Im able to use the position and rotation to do plenty of other things and it all works great except this last piece I cant figure out. Code samples run in the Target's class, Position the targets position, Avatar the player. EDIT Im now using Maik's c code he has provided and it works great! |
12 | Problems making my basketball bounce around horizontally This is probably a very easy question, but I can't seem to understand why it's not working. I want the basketball to bounce horizontally when it touches the borders on the right and left, but when it bounces on the right, it seems to go just a little bit further than it should. Any suggestions? protected override void Update(GameTime gameTime) Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back ButtonState.Pressed) this.Exit() basketballPosition.X ballSpeed if (basketballPosition.X gt Window.ClientBounds.Width basketball.Width basketballPosition.X lt 0) ballSpeed 1 base.Update(gameTime) And my Draw method protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.CornflowerBlue) spriteBatch.Begin() spriteBatch.Draw(basketball, basketballPosition, null, Color.White, 0, Vector2.Zero, 1.5f, SpriteEffects.None, 0) spriteBatch.End() base.Draw(gameTime) Edit The problem was I was using a scale of 1.5f for drawing the image. Can someone explain how I would get the true border of the image if I were using scale? It seems the border stay as the original size, but the texture is drawn to whatever scale I choose. |
12 | Voice Commands Using Microphone Possible Duplicate Voice input in games beyond voip chat I recently made a game where you say something into the microphone, and the computer repeats it, but I was wondering how to make voice commands, where if you say a certain thing it does something. For example I say "Blue" and the background color changes to blue. I say "Red" and the background color changes to red. |
12 | How do I rotate a single object in HLSL? I have a World with a 3D model of a head in it and that World rotates, like such protected override void Update(GameTime gameTime) other stuff angle 0.00005f more other stuff protected override void Draw(GameTime gameTime) other stuff Matrix rotation Matrix.CreateRotationY(3 angle) effect.Parameters "World" .SetValue(rotation Matrix.CreateScale(10.0f)) other stuff And then in my Effects file I create a spotlight float4 SimplePixelShader(VertexShaderOutput input) COLOR0 float4 lightDirection 1, 1, 1, 0 float theta 10.0f float phi 30.0f float4 color float4 lambert DiffuseColor 0.2 max(0, dot(input.Normals, input.lambertLightDir)) float angle acos(dot(input.lightDir, normalize(lightDirection))) if(angle gt radians(phi)) color AmbientColor AmbientIntensity else if(angle lt radians(theta)) color lambert else color max(AmbientColor AmbientIntensity, smoothstep(radians(phi), radians(theta), angle) lambert) return color And naturally this spotlight also rotates with the world. However, I dont want it to rotate. I tried everything, multiplying, adding, subtracting the rotation matrix and or the angle from the different lightdirections and angles and nothing works. Now I could rotate just the model and not the world, that would even be a sensible thing to do, but I have no clue how P So I'm either looking for a good way to rotate the model or a way to 'counter rotate' the spotlight so it seems to stand still. Edit my vertexshader VertexShaderOutput SimpleVertexShader(VertexShaderInput input) some other vertexshaderstuff float4 lightPoint 3, 2, 2, 0 output.lightDir normalize(input.Position3D) lightPoint output.lambertLightDir float4(30, 30, 20, 0) return output |
12 | XNA SoundEffect won't stop playing For my HND I've got to re create Frogger, and everything was going swell until I tried adding some collision detection and sound. Whenever my player intersects a vehicle, the sound file just starts playing with every game update instead of just once. Here is my code from the update method if (vehicles count .bbox.Intersects(playerSprites lives .bbox)) playerSprites lives .isDead true if (playerSprites lives .isDead) deathSound.Play() The sound is declared as a SoundEffect, loaded as a SoundEffect, and the content processor is set to Sound Effect, and as far as I can tell, Sound Effects in XNA are only meant to be played once. What am I doing wrong?? |
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 | XNA DrawIndexedPrimitives or DrawUserIndexedPrimitives? When rendering primitives in XNA, does it matter if I use DrawIndexedPrimitives() versus DrawUserIndexedPrimitives()? RB Whitaker uses the former, while Reimer's uses the latter. From what I can tell, the intent is that if you're using a premade type that ships with XNA (such as VertexPositionNormalTexture), you should use the normal draw primitives function, while if you create a custom struct which satisfies IVertexType and or VertexDeclaration, you should use the DrawUserPrimitives instead. However, XNA places no such restriction on how they're used, and I am wondering why it wasn't just all rolled into one generic function to begin with. |
12 | XNA Error while rendering a texture to a 2D render target via SpriteBatch I've got this simple code that uses SpriteBatch to draw a texture onto a RenderTarget2D private void drawScene(GameTime g) GraphicsDevice.Clear(skyColor) GraphicsDevice.SetRenderTarget(targetScene) drawSunAndMoon() effect.Fog true GraphicsDevice.SetVertexBuffer(line) effect.MainEffect.CurrentTechnique.Passes 0 .Apply() GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2) GraphicsDevice.SetRenderTarget(null) SceneTexture targetScene private void drawPostProcessing(GameTime g) effect.SceneTexture SceneTexture GraphicsDevice.SetRenderTarget(targetBloom) spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque, null, null, null) if (Bloom) effect.BlurEffect.CurrentTechnique.Passes 0 .Apply() spriteBatch.Draw( targetScene, new Rectangle(0, 0, Window.ClientBounds.Width, Window.ClientBounds.Height), Color.White) spriteBatch.End() BloomTexture targetBloom GraphicsDevice.SetRenderTarget(null) Both methods are called from my Draw(GameTime gameTime) function. First drawScene is called, then drawPostProcessing is called. The thing is, when I run this code I get an error on the spriteBatch.Draw call The render target must not be set on the device when it is used as a texture. I already found the solution, which is to draw the actual render target (targetScene) to the texture so it doesn't create a reference to the loaded render target. However, to my knowledge, the only way of doing this is to write GraphicsDevice.SetRenderTarget(outputTarget) SpriteBatch.Draw(inputTarget, ...) GraphicsDevice.SetRenderTarget(null) Which encounters the same exact problem I'm having right now. So, the question I'm asking is how would I render inputTarget to outputTarget without reference issues? |
12 | XNA's SetData in a SharpDX Texture2D object in DirectX 11? I'm trying to load a texture given a swap chain, and then populate that texture with data. I already have some bitmap data (although not sure if it is in the correct format) that I want to populate the texture with. However, XNA's SetData method of the Texture2D object is obviously not present in SharpDX. What do I do to populate my texture with data? I load the texture using the following code. var texture Resource.FromSwapChain lt Texture2D gt (swapChain, 0) |
12 | How do I ensure that my 2D side scroller camera stays within the world bounds? I have tried implementing a basic 2D sidescroller camera in XNA, but I don't want it to be able to scroll past the edges of my tile map! I tried to fix it, but when I get the left side working, the right stops working... How do I do this right? EDIT After Anko public Matrix transform Viewport view Vector2 center public void Update(GameTime gameTime, Player player) center new Vector2(player.Position.X (player.Bounds.Width 2) (960 2), 0) float cameraX center.X float cameraWidth view.Width float worldWidth 1760 if (cameraX lt 0) cameraX 0 else if ( cameraX cameraWidth gt worldWidth) cameraX worldWidth cameraWidth transform Matrix.CreateTranslation(new Vector3( cameraX, 0, 0)) |
12 | How can I cleanly separate the UI from the game logic in my Cocos2d game? I've been working on a little game for the last few months, trying to approach it as a software engineer and employ best patterns and practices in my coding. I have gotten to the point where I have to distinct elements in my game. The Game Logic aka business logic. Its the meat of the game rules. It contains all information about game objects (such as Character, Weapon, and Item class definitions). It contains the game world as far as rules are required mainly so Characters are aware of the world they are in, and who else is in it. It contains a chunk of logic use to determine how Fighting is resolved between Characters, as we as other game actions requiring rules. It contains my AI implementations. So in reality it's a combination of Class definitions and Service logic. As it stands, the Game Logic can actually play out a game without any interface. All I need to do is create a World, add some Characters to it, assign some AI's to them, then in a loop tell their AIs to run. The result of each AIs action is reflected in the states of the Characters (eg, if damaged, health is reduced), and a summary of what happened is returned by the execution (which is intended for the UI to make sense of what happened). The Game UI which is using Cocos2d xna for WP7. It contains definitions of all the different animations. It takes in inputs and sends the to the Game Logic, and renders its results. As it stands, as well as all UI components for a Character (textures, sprites, animations) a UI Character also contains a Begin method which executes a Cocos2d Sequence (ccSequence) to do two things 1) Execute AI and render result for this Character 2) Re Execute the sequence (essentially its own call back loop for executing actions). The problem I keep running into is, the more I try to keep these two layers separate, the more they need to come together. E.g., my UI Character which is used to render what the Game Logic character is doing, so it needs a reference to the Character object from Game Logic. When this Character's AI attacks someone in the Game Logic world, the UI needs to know what happened. This works fine for rendering its own Animations based of its results, but to know what to do for other Characters affected by this action is difficult as I dont have reference to them. At the moment I do this by queuing up Pending Animations in the other character's Game Logic Character and render it when that character next executes, but this is anti SoC (Separation of Concerns) as it now contains something specific for the UI to focus on. I don't want the two projects to merge into one where a Game Logic Character contains all things UI as well, such as animations and actions. Is there a nice clean way that is used for this separation? Ideally something that works nicely with Cocos2d's Action pattern? |
12 | Texture visualization problem on camera movement (xna) I'm trying to move a camera over a model that is used as the floor of the game. When I move the camera, the texture of the model is not showing correctly (video of the problem http www.youtube.com watch?v bpycA7epMns amp feature youtu.be). I know that the model is fine because i use xnamodelviewer (http modelviewer.codeplex.com ) to preview all the models, and i can see it all right, even if i move the camera. So, the problem is in my model class maybe? what is wrong with this? any help is appreciated. this is the model class im using public class CModel public Vector3 Position get set public Vector3 Rotation get set public Vector3 Scale get set public Model Model get private set private Matrix modelTransforms private GraphicsDevice graphicsDevice private BoundingSphere boundingSphere public BoundingSphere BoundingSphere get No need for rotation, as this is a sphere Matrix worldTransform Matrix.CreateScale(Scale) Matrix.CreateTranslation(Position) BoundingSphere transformed boundingSphere transformed transformed.Transform(worldTransform) return transformed public CModel(Model Model, Vector3 Position, Vector3 Rotation, Vector3 Scale, GraphicsDevice graphicsDevice) this.Model Model modelTransforms new Matrix Model.Bones.Count Model.CopyAbsoluteBoneTransformsTo(modelTransforms) buildBoundingSphere() this.Position Position this.Rotation Rotation this.Scale Scale this.graphicsDevice graphicsDevice private void buildBoundingSphere() BoundingSphere sphere new BoundingSphere(Vector3.Zero, 0) Merge all the model's built in bounding spheres foreach (ModelMesh mesh in Model.Meshes) BoundingSphere transformed mesh.BoundingSphere.Transform( modelTransforms mesh.ParentBone.Index ) sphere BoundingSphere.CreateMerged(sphere, transformed) this.boundingSphere sphere public virtual void Draw(Matrix View, Matrix Projection,bool luces) Calculate the base transformation by combining translation, rotation, and scaling Matrix baseWorld Matrix.CreateScale(Scale) Matrix.CreateFromYawPitchRoll(Rotation.Y, Rotation.X, Rotation.Z) Matrix.CreateTranslation(Position) foreach (ModelMesh mesh in Model.Meshes) Matrix localWorld modelTransforms mesh.ParentBone.Index baseWorld foreach (ModelMeshPart meshPart in mesh.MeshParts) BasicEffect effect (BasicEffect)meshPart.Effect effect.World localWorld effect.View View effect.Projection Projection if (luces true) effect.LightingEnabled true else effect.EnableDefaultLighting() graphicsDevice.DepthStencilState DepthStencilState.Default mesh.Draw() If I disable the line graphicsDevice.DepthStencilState DepthStencilState.Default The problem with the texture is solved, but i now have problems with the model showing things that must be hidden behind others, like in this picture |
12 | When to use GameComponents? I know what it is and I'm using it as a frame counter for example. But when should I use it? Does it make sense to say "I make all the input handling happen in a gamecomponent"? Is it flexible enough to add and remove fast in runtime? I see I can set the update order and draw order, but I guess to keep track of it an enum should be best like "GamePadInput 0" or "MessageBox 100". Or should I just design simple, for example when I want to determinate if a messagebox is open checking "if (MessageBox.Active)" and then manually updating drawing? I'm a bit confused and can't decide what to do. I don't want to start designing the game and see later "oops". Maybe you can help me out ) |
12 | XNA 4.0 Model into parts is there a way to split a .fbx model into parts, and move those parts individualy in XNA 4.0 ? Thanks |
12 | Obtaining a world point from a screen point with an orthographic projection I assumed this was a straightforward problem but it has been plaguing me for days. I am creating a 2D game with an orthographic camera. I am using a 3D camera rather than just hacking it because I want to support rotating, panning, and zooming. Unfortunately the math overwhelms me when I'm trying to figure out how to determine if a clicked point intersects a bounds (let's say rectangular) in the game. I was under the impression that I could simply transform the screen point (the clicked point) by the inverse of the camera's View Projection matrix to obtain the world coordinates of the clicked point. Unfortunately this is not the case at all I get some point that seems to be in some completely different coordinate system. So then as a sanity check I tried taking an arbitrary world point and transforming it by the camera's View Projection matrices. Surely this should get me the corresponding screen point, but even that didn't work, and it is quickly shattering any illusion I had that I understood 3D coordinate systems and the math involved. So, if I could form this into a question How would I use my camera's state information (view and projection matrices, for instance) to transform a world point to a screen point, and vice versa? I hope the problem will be simpler since I'm using an orthographic camera and can make several assumptions from that. I very much appreciate any help. If it makes a difference, I'm using XNA Game Studio. |
12 | Creating a 2D Line Branch (Part 2) Yesterday i asked this question on how to create a 2D line branch Creating a 2D Line Branch And thanks to the answered provided, i now have this nice looking main branch coloured to show the different segments in the final item. Now is the time now to branch things off as discussed in the article http drilian.com 2009 02 25 lightning bolts Again however i am confused as to the meaning of the following pseudo code splitEnd Rotate(direction, randomSmallAngle) lengthScale midPoint I'm unsure how to actually rotate this correctly. In all honesty i'm abit unsure what to do completely at this part, "splitEnd" will be a Vector3, so whatever happens in the rotate function must then return some form of directional rotation which is then by a scale to create length and then added to the midPoint. I'm not sure. If someone could explain what i'm meant to be doing in this part that would be really grateful. |
12 | ContentSerializerRuntimeType required in content pipeline? I have a problem at the moment loading in a texture for a larger model in the content pipeline. Now it seems that I need to make a proxy object, which is fine, however looking at the SpriteSheet example provided by Microsoft they seem to use the ContentSerializerRuntimeType attribute to bind the proxy class to the real class for use at runtime. The problem is they sprinkle serialization attributes all over the runtime class, so I was wondering if you HAVE to do it this way or if it is just a recommendation, and is there any other way of getting your proxy class to the real instance? Ideally I dont want to have to put attributes all over my classes and would be more than happy to write the serialization code myself if there was a way to, but it seems to be an unknown as far as the documentation goes for this area... So anyone know a way round this, or is this just the only way to do it? |
12 | Does XNA have a built in GUI library? Does such a thing exist or do I have to code one? My project needs textboxes, buttons, input capture, timings for "press and hold keys" and so on. These are quite standard for a GUI library but hard to code from scratch. What options do I have? |
12 | Why does transforming a Vector3 by a Quaternion result in reversed Z? I'm trying to transform the vector (1, 0, 0) by an orientation unit quaternion, which in XNA should be Vector3 v Vector3.Transform(Vector3.Right, Orientation) But this results in the Z value reversed from its expected value for example, transforming Vector3.Right by Orientation (0.6532815, 0.270598, 0.270598, 0.6532815) results in the vector (0, 0.7071, 0.7071) when it should result in the vector (0, 0.7071, 0.7071). I found another implementation here Quaternion o Orientation Vector3 oV new Vector3(o.X, o.Y, o.Z) Vector3 v 2 Vector3.Cross(oV, Vector3.Right) v Vector3.Right o.W v Vector3.Cross(oV, v) But that results in the same problem. Reversing the Z value is trivial, but I'm worried that if I don't find a solution to this now the problem will manifest some other way down the road. Especially since, up until now, I thought I was playing by XNA's rules in my game engine (same coordinate system, same handedness). For reference, this code I wrote does produce the expected result in my engine Vector3 v Quaternion o OrientationGlobal double y Math.Atan2(2 (o.W o.Z o.X o.Y), 1 2 (o.Z o.Z o.Y o.Y)) yaw about global Z axis v.Z MathHelper.Clamp(2 (o.W o.Y o.Z o.X), 1, 1) double m Math.Sqrt(1 v.Z v.Z) v.X (float)(m Math.Cos(y)) v.Y (float)(m Math.Sin(y)) What am I missing? |
12 | How to draw text on a 3d sphere? I am facing a problem in mapping 3d co ordinate to screen co ord . I require it because i want to draw text on the model . model is drawn at the 3d cordinate, so if i know the position of that co ord on the screen i can draw text at that position. my view is on z axis test position is on x axis In the follwing code I did what i said above but the transformation is not happening the way it should i.e, text should appear on the model float aspectRatio graphics.GraphicsDevice.Viewport.AspectRatio Vector2 screenOrigin new Vector2(GraphicsDevice.Viewport.Width 2, GraphicsDevice.Viewport.Height 2) Vector3 testPosition new Vector(10,0,0) Vector3 cameraPosition new vector(0,0,50), Matrix world Matrix.Identity Matrix view Matrix.CreateLookAt(cameraPosition,Vector3.Zero, Vector3.Up) Matrix projection Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f) Matrix totalEffect world view projection Vector2 spritePos getXYPosition(vecAndMatMultiplication(testPosition, totalEffect)) screenOrigin Where vecAndMatMultiplication() multiplies vector with the matrix and getXYpostion() should be fairly obvious. |
12 | Having troubles with LibNoise.XNA and generating tileable maps Following up on my previous post, I found a wonderful port of LibNoise for XNA. I've been working with it for about 8 hours straight and I'm tearing my hair out I just can not get maps to tile, I can't figure out how to do this. Here's my attempt Perlin perlin new Perlin(1.2, 1.95, 0.56, 12, 2353, QualityMode.Medium) RiggedMultifractal rigged new RiggedMultifractal() Add add new Add(perlin, rigged) Initialize the noise map int mapSize 64 this.m noiseMap new Noise2D(mapSize, perlin) this.m noiseMap.GeneratePlanar(0, 1, 1, 1) Generate the textures this.m noiseMap.GeneratePlanar( 1,1, 1,1) this.m textures 0 this.m noiseMap.GetTexture(this.graphics.GraphicsDevice, Gradient.Grayscale) this.m noiseMap.GeneratePlanar(mapSize, mapSize 2, mapSize, mapSize 2) this.m textures 1 this.m noiseMap.GetTexture(this.graphics.GraphicsDevice, Gradient.Grayscale) this.m noiseMap.GeneratePlanar( 1, 1, 1, 1) this.m textures 2 this.m noiseMap.GetTexture(this.graphics.GraphicsDevice, Gradient.Grayscale) The first and third ones generate fine, they create a perlin noise map however the middle one, which I wanted to be a continuation of the first (As per my original post), is just a bunch of static. How exactly do I get this to generate maps that connect to each other, by entering in the mapsize tile, using the same seed, settings, etc.? |
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 | Resizing a parallax background (bug) I'm attempting my first 2D vertical scroller and can't seem to get the background size to work. For some reason, it stays small. I think in the beginning of the parallax scrolling class, I was told to initialize variables and I know which ones I have to change. public Texture2D picture public Vector2 position Vector2.Zero public Vector2 offset Vector2.Zero public float depth 0.0f public float moveRate 0.0f public Vector2 pictureSize Vector2.Zero public Color color Color.White I think I must change pictureSize to make it bigger, as the current sizing I get this Finally, how can I remove the whitespace from the ship image? EDIT Here is the code for the rendering of the actual ship public void Render(SpriteBatch batch) batch.Begin() batch.Draw(shipSprite, position, null, Color.White, 0.0f, spriteOrigin, 1.0f, SpriteEffects.None, 0.0f) batch.End() The whitespace seems to be provided by XNA as I've tried clearing it using Photoshop. Because I can't directly upload to the site, I have put it here This renders the background public void Draw() layerList.Sort(CompareDepth) batch.Begin() for (int i 0 i lt layerList.Count i ) if (!moveLeftRight) if (layerList i .position.Y lt windowSize.Y) batch.Draw(layerList i .picture, new Vector2(0.0f, layerList i .position.Y), layerList i .color) if (layerList i .position.Y gt 0.0f) batch.Draw(layerList i .picture, new Vector2(0.0f, layerList i .position.Y layerList i .pictureSize.Y), layerList i .color) else batch.Draw(layerList i .picture, new Vector2(0.0f, layerList i .position.Y layerList i .pictureSize.Y), layerList i .color) else if (layerList i .position.X lt windowSize.X) batch.Draw(layerList i .picture, new Vector2(layerList i .position.X, 0.0f), layerList i .color) if (layerList i .position.X gt 0.0f) batch.Draw(layerList i .picture, new Vector2(layerList i .position.X layerList i .pictureSize.X, 0.0f), layerList i .color) else batch.Draw(layerList i .picture, new Vector2(layerList i .position.X layerList i .pictureSize.X, 0.0f), layerList i .color) batch.End() (It's from a XNA tutorial book I'm reading.) |
12 | Timestep in multiplayer game I'm trying to wrap my brain around the concept of creating a server client multiplayer experience. My problem is mainly related to timestep. Consider the following scenario A client connects to a server. The client sends his inputs to the server to indicate he wants to move. Server simulates the input and determines the position of that client in the game world. Since the client and the server are both running on different timesteps, how do you accurately simulate so that all clients are in sync with the server? My server is currently set at at 30ms timestep. When I process client movements, there are potentially hundreds of requests waiting to be processed, yet no way to indicate how long it took between each one of the requests. I'm really not grasping how to properly simulate on the server based on time, in order to have everything sync up. |
12 | Switching to a vertex shader TL DR I need to switch from a vertex array passed to the pixel shader with a real vertex shader approach. In my prototype, the terrain is procedurally generated and I have the following result The terrain vertices are passed directly to the pixel shader through an array Number of vertices in terrain array static const int verticesCount 20 The vertices array, in pixel coordinates float2 terrain verticesCount A fixed distance between neighbor vertices float fixedDistance float4 PixelShaderFunction(float2 pixelCoords VPOS, float2 textureCoords TEXCOORD0) COLOR0 float4 color tex2D(s0, textureCoords) int i pixelCoords.x fixedDistance float delta (pixelCoords.x terrain i .x) (terrain i 1 .x terrain i .x) if(smoothInterpolate(terrain i .y, terrain i 1 .y, delta) gt pixelCoords.y) color.rgba 0 return color As you can see I just interpolate between the vertices and mask the texture to the terrain. Now I need a different approach because I'm using a view matrix for the camera and it does not affect these vertices that do not go through the vertex shader, how can I replace the terrain array with a vertex shader to get a similar result? All suggestions are welcome! |
12 | Xna, after mouse click cpu usage goes 100 Hi i have following code and it is enough just if i click on blue window then cpu goes to 100 for like at least one minute even with my i7 4 cores. I just check even with empty project and is the same !!! public class Game1 Microsoft.Xna.Framework.Game GraphicsDeviceManager graphics SpriteBatch spriteBatch private Texture2D cursorTex private Vector2 cursorPos GraphicsDevice device float xPosition float yPosition public Game1() graphics new GraphicsDeviceManager(this) Content.RootDirectory "Content" protected override void Initialize() Viewport vp GraphicsDevice.Viewport xPosition vp.X (vp.Width 2) yPosition vp.Y (vp.Height 2) device graphics.GraphicsDevice base.Initialize() protected override void LoadContent() spriteBatch new SpriteBatch(GraphicsDevice) cursorTex Content.Load lt Texture2D gt ("strzalka") protected override void UnloadContent() TODO Unload any non ContentManager content here protected override void Update(GameTime gameTime) Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back ButtonState.Pressed) this.Exit() base.Update(gameTime) protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.CornflowerBlue) spriteBatch.Begin() spriteBatch.Draw(cursorTex, cursorPos, Color.White) spriteBatch.End() base.Draw(gameTime) |
12 | Unknown error XNA cannot detect importer for "program.cs" I am not too sure what I have done to cause this, but even after undoing all my edits, this error still appears Error 1 Cannot autodetect which importer to use for "Program.cs". There are no importers which handle this file type. Specify the importer that handles this file type in your project. (filepath) Advanced Pong AdvancedPongContent Program.cs Advanced Pong After receiving this error, everything between if and endif in the program.cs fades grey using System namespace Advanced Pong if WINDOWS XBOX static class Program lt summary gt The main entry point for the application. lt summary gt static void Main(string args) using (Game1 game new Game1()) game.Run() endif I have searched this and could not find a solution anywhere. Any help is appreciated. |
12 | Should I use XNA or Unity to build a video game? My friend and I are planning to make a video game (like Slender) where the character is stuck in a building, when lightning strikes, and the lights go out and your objective is to find the back up generators and turn the lights back on. The game will be pretty small.We are now wondering whether we should use Unity or XNA to build it. I have no experience in either, and I will mostly be writing in C (which both have that capability). My friend will be drawing the images, and we want to import the images into the game. Which software should we use? What are the pros and cons of each? Thanks in advance. |
12 | How to force playing attack animation until the end? I rework the code to make it more easier to manage. How can I force the player cannot change the sprite animation by pressing any keys until the attack animation completely ends? class Player Animation playerIdle Animation playerRun Animation playerAtk public void Load(ContentManager content) playerIdle new Animation(content, "idle", 144, 128, 8, 30) playerRun new Animation(content, "run", 160, 112, 8, 30) playerAtk new Animation(content, "atk", 154, 131, 2, 30) playerIdle.EnableRepeating() playerRun.EnableRepeating() playerAtk.EnableRepeating() public void Update(GameTime gameTime) playerIdle.Update(gameTime) UpdateControl(gameTime) region Update Control string selectSpriteSheet KeyboardState mPreviousKeyboardState SpriteEffects spriteEffects SpriteEffects.FlipHorizontally Vector2 feetPosition new Vector2(0, 350) Vector2 mSpeed Vector2.Zero Vector2 mDirection Vector2.Zero Vector2 mStartingPosition Vector2.Zero int CHARACTER SPEED 50 int MOVE LEFT 5 int MOVE RIGHT 5 int MOVE UP 5 int MOVE DOWN 5 enum State Running, Jumping, Attacking, State mCurrentState State.Running public void UpdateControl(GameTime gameTime) KeyboardState aCurrentKeyboardState Keyboard.GetState() feetPosition mDirection mSpeed (float)gameTime.ElapsedGameTime.TotalSeconds selectSpriteSheet "idle" UpdateMovement(aCurrentKeyboardState, gameTime) UpdateJump(aCurrentKeyboardState, gameTime) mPreviousKeyboardState aCurrentKeyboardState private void UpdateMovement(KeyboardState aCurrentKeyboardState, GameTime gameTime) if (mCurrentState State.Running) mSpeed Vector2.Zero mDirection Vector2.Zero if (aCurrentKeyboardState.IsKeyDown(Keys.Left) amp amp !aCurrentKeyboardState.IsKeyDown(Keys.Right)) playerRun.Update(gameTime) selectSpriteSheet "run" spriteEffects SpriteEffects.None mSpeed.X CHARACTER SPEED mDirection.X MOVE LEFT else if (aCurrentKeyboardState.IsKeyDown(Keys.Right) amp amp !aCurrentKeyboardState.IsKeyDown(Keys.Left)) playerRun.Update(gameTime) selectSpriteSheet "run" spriteEffects SpriteEffects.FlipHorizontally mSpeed.X CHARACTER SPEED mDirection.X MOVE RIGHT if (aCurrentKeyboardState.IsKeyDown(Keys.Z) amp amp mPreviousKeyboardState.IsKeyUp(Keys.Z)) mCurrentState State.Attacking if (mCurrentState State.Attacking) playerAtk.Update(gameTime) selectSpriteSheet "hit" mCurrentState State.Running endregion public void Draw(SpriteBatch spriteBatch) playerIdle.Draw(spriteBatch, feetPosition, (float)MathHelper.ToRadians(0), 1.0f) if (selectSpriteSheet "idle") playerIdle.Draw(spriteBatch, feetPosition, spriteEffects, (float)MathHelper.ToRadians(0),1.0f) else if (selectSpriteSheet "run") playerRun.Draw(spriteBatch, feetPosition, spriteEffects, (float)MathHelper.ToRadians(0),1.0f) else if (selectSpriteSheet "hit") playerAtk.Draw(spriteBatch, feetPosition, spriteEffects, (float)MathHelper.ToRadians(0), 1.0f) |
12 | XNA drawing textures on random positions I'm trying to reproduce this tutorial, but each time I try to implement it into my code, I always get a lot of errors. Now I finally managed to code something like this, the game runs, but nothing happens at all, my screen remains black without any texture drawn on it, and I just can't figure out what am I doing wrong here. Here's my background class public class background public Vector2 position public Texture2D texture private List lt Star gt stars private Random Random private int MaxX private int MaxY private int Intensity public background(ContentManager content, int Intensity) this.texture content.Load lt Texture2D gt ("star2") Intensity Intensity this.MaxX 1280 this.MaxY 720 stars new List lt Star gt () Random new Random(DateTime.Now.Millisecond) for (int i 0 i lt Intensity i ) int StarColorR Random.Next(25, 100) int StarColorG Random.Next(10, 100) int StarColorB Random.Next(90, 150) int StarColorA Random.Next(10, 50) stars.Add(new Star(new Vector2( Random.Next(MaxX 2 1280, MaxX 2 720), Random.Next(MaxY 2 1280, MaxY 2 720)), new Color(StarColorR 3, StarColorG 3, StarColorB 3, StarColorA 3))) public void Update(GameTime gameTime) public void Draw(SpriteBatch spriteBatch) spriteBatch.Begin() foreach (Star s in stars) spriteBatch.Draw(texture, s.Position, s.Color) spriteBatch.End() And the stars class class Star public Vector2 Position public Color Color public Star(Vector2 Position, Color Color) this.Position Position this.Color Color As you can see I'm not using the exact same Star class as it is in the original code. First, I'm just trying to achieve the stars to appear on the game screen in random positions. |
12 | How to convert Texture2DContent to Texture2D in custom ContentTypeReader I'm trying to implement a custom ContentPipeline extension that writes a Surface object with a Texture2D member. My input file is an xml with fields for all of my Surfaces and their members. In the xml, my Surface's Texture2D is represented by a path to an image file. In my ContentProcessor, I want to load the Texture2D from the image file path, then write that texture data straight into my object's xnb with the rest of a Surface's members. Right now, I've got the ContentTypeWriter writing a different ("CompiledSurface") object with a Texture2DContent member. The Texture2DContent is created in the ContentProcessor using BuildAndLoadAsset(string path). My importer, processor, and writer all seem to be doing their jobs. But in my ContentTypeReader, I can't figure out how to convert the Texture2DContent back to a Texture2D in order to create my runtime object. Any help is much appreciated. class Surface protected Rectangle bounding box protected Texture2D texture ... class CompiledSurface public Texture2DContent texture public int x public int y ... |
12 | Which type of Xbox console should I get to begin developing games on it? If I want to start developing small indie like games with XNA on Xbox (I don't think any game I'd make would need more than 100, maybe 200 megabytes), will the 4gb Slim (I want to get a slim version because of the wi fi) version of the console be enough, or should I get the 250 gb version? I don't really plan to play actively on the console as I'm more interested in developing on it. Also, will a console and a verified student XBLIG account be enough to set up everything I need to run and debug my game on the console? Thank you. |
12 | Math behind XNA's spriteBatch.draw() color parameter? I'm trying to make a shader that changes the color of a sprite the way the XNA spriteBatch.draw() color parameter changes color. I don't know exactly what it is called (the closest word I can think of is 'tinting' but that's not right I don't think) and it's kind of hard to explain the way it looks. Say you set the parameter to 'Red' white pixels in the original texture would become completely red, while black pixels would remain black. Grey pixels would look dark red, blue pixels might look purple, green pixels might look brownish. If you set the parameter to 'Black' the texture would become completely black. Does anyone know the math behind this, or what this technique is called? It's probably very simple and I'm just not seeing it. Thanks! |
12 | How to order objects with the same depth in the spritebatch cycle? I have a tilemap in a isometric 2.5 view and i have also many objects moving and static. The problem is many statics are standing in a "integer" place for obvious reasons and the depths of each object is calculated based on their position in the tilemap. So what happens for some strage reasons is that 2 objects standing next to each other if big enough overlap and if they are in an adjacent diagonal tile they also have the same exact depth, but when drawing the order of same depth object seems random... I draw them in the same order every cycle ofc but the overlapped part of the texture sort of flicker being drawed on top or bottom apparently randomly... Is there a way to use depth to order objects but make the same depth ones be in some kind of order and not random? |
12 | Programming and drawing to deal with different screen sizes and resolutions I started making an XNA game years ago and picked it up recently. I'm looking later to convert it to use Monogame so that it can be deployed on various mobile devices and OS, though I have a sinking feeling that a lot of the sprites and code will be broken by the changing screen sizes when I move outside of the emulator. The game is currently hard coded to to 800x480 and the level placements and sprite sizes were all done to fit that at the time. So question What do I need to ensure this works and displays properly on a variety of screens and devices? |
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 | 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 | Loading levels in XNA from XML I'm trying to load levels in XNA from XML files. I have currently got a system to do this working, but it looks like it might get horribly complex as I add more objects later on. My world currently consists of Planet entities along with physics props, scenery, static props, etc. It will later include NPCs, interactive machines, and a lot more content (but I want to sort this out before going any further). Based on a tutorial I read, my level loader loads a LevelData entity from XML. This contains arrays of PlanetLevelData, PropData, and StaticData. My test file is as shown lt ?xml version "1.0" encoding "utf 8" ? gt lt XnaContent gt lt ! TODO replace this Asset with your own XML asset data. gt lt Asset Type "DataTypes.LevelData" gt lt PlanetData gt lt Item gt lt Position gt 5.2 5.2 lt Position gt lt BodyRadius gt 300 lt BodyRadius gt lt FieldRadius gt 450 lt FieldRadius gt lt Name gt Jupiter lt Name gt lt Rotation gt 0 lt Rotation gt lt ImageName gt lt ImageName gt lt Item gt lt Item gt lt Position gt 2 2 lt Position gt lt BodyRadius gt 300 lt BodyRadius gt lt FieldRadius gt 450 lt FieldRadius gt lt Name gt Jupiter2 lt Name gt lt Rotation gt 0 lt Rotation gt lt ImageName gt lt ImageName gt lt Item gt lt PlanetData gt lt PropData gt lt Item gt lt Type gt Crate lt Type gt lt Position gt 2 3 lt Position gt lt Item gt lt PropData gt lt StaticData gt lt Item gt lt Type gt FromImage lt Type gt lt Position gt 4.5 4.5 lt Position gt lt ImagePath gt Lamp lt ImagePath gt lt Rotation gt 2 lt Rotation gt lt Radius gt 0 lt Radius gt lt Vertices gt lt Vertices gt lt PlanetOwner gt Jupiter2 lt PlanetOwner gt lt Item gt lt StaticData gt lt Asset gt lt XnaContent gt In other words, I have to put all my content files into arrays. However, for me to have different types of StaticData from the XML file, I have to specify the type with a String (called Type). I then load the XML using Content.Load lt LevelData gt ("name here.xml"). I go through every PlanetData in the array and create a new Planet based on it's properties. I also use switch statements based on the Type field to specify which type to create... Is this the only way to load level data into objects using XML (I hope not, it's hideous to use). I couldn't really find much on this topic... |
12 | Can you write games for Rock Band or Guitar Hero controllers in XNA? Can you use the XNA framework to write games for XBox Live Arcade that require Rock Band or Guitar Hero instruments? |
12 | Is multipass rendering possible with SpriteBatch? I'm trying to implement a bloom effect. This requires three shader passes a brightness threshold, a horizontal blur, and a vertical blur. It also requires resizes, but these are irrelevant to the question. I've also omitted the threshold, as the problem lies in the blurs. Now, I've read that HLSL passes are just syntactic sugar for different shaders, and that switching between them is about as expensive as setting a new effect to the GraphicsDevice. Still, I prefer to keep them in one .fx file. The passes pass Pass0 PixelShader compile ps 2 0 PS Threshold() pass Pass1 PixelShader compile ps 2 0 PS BlurHorizontal() pass Pass2 PixelShader compile ps 2 0 PS BlurVertical() The blurring code private void Blur(SpriteBatch SpriteBatch, RenderTarget2D Source, RenderTarget2D Rendertarget1, RenderTarget2D Destination) Blur pass 1 Contents.BloomEffect.CurrentTechnique.Passes "Pass1" .Apply() SpriteBatch.GraphicsDevice.SetRenderTarget(Rendertarget1) SpriteBatch.GraphicsDevice.Clear(Color.Black) SpriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, Contents.BloomEffect) SpriteBatch.Draw(Source, Rendertarget1.Bounds, Color.White) SpriteBatch.End() Blur pass 2 Contents.BloomEffect.CurrentTechnique.Passes "Pass2" .Apply() SpriteBatch.GraphicsDevice.SetRenderTarget(Destination) SpriteBatch.GraphicsDevice.Clear(Color.Black) SpriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, Contents.BloomEffect) SpriteBatch.Draw(Rendertarget1, Destination.Bounds, Color.White) SpriteBatch.End() Finally, the Draw loop protected override void Draw(GameTime gameTime) GraphicsDevice.SetRenderTarget(RT1) GraphicsDevice.Clear(Color.CornflowerBlue) spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, bloom) spriteBatch.Draw(android, new Rectangle(0, 0, 258, 294), Color.White) spriteBatch.End() Blur(spriteBatch, RT1, RT11, RT1) GraphicsDevice.SetRenderTarget(null) GraphicsDevice.Clear(Color.Black) spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive, null, null, null, null) spriteBatch.Draw(RT1, RT1.Bounds, Color.White) spriteBatch.End() base.Draw(gameTime) The output, however, is as follows It's obvious what happens the last pass is applied twice. I've tested the passes individually by snipping them out of the shader, and they work fine. Is EffectPass.Apply() simply not meant to be used with SpriteBatch, or is there another way to change what passes are applied (without putting the passes in different .fx files)? This has all been in XNA. To make this even weirder, when I do the same thing in Monogame the opposite occurs the shader will only use Pass0. However, I'm converting the shader to OpenGL there, so that might be a conversion quirk. EDIT I fixed this by putting the different passes in different techniques, and switching techniques instead of passes. That doesn't answer the original question though, so I'll leave it open. |
12 | How do I modify a Boids algorithm to be player controlled? Found source code on Boids in C . http 3carrotsonastick.wordpress.com 2012 11 01 boids in c xna How do I go about making the raven class in the above player controlled? If I could control it myself, it would be a great help, but I don't know how to go about it. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.