_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
12 | 2D Mask antialiasing in xna hlsl I have two texture2d , one of these is a mask texture and have 2kind color and i use that for mask (filter) second texture2D something like float4 tex tex2D(sprite, texCoord) float4 bitMask tex2D(mask, texCoord) if (bitMask.a gt 0) return float4(0,0,0,0) else return float4(tex.b,tex.g,tex.r,1) but because mask texture is just two color the result is too jagged i want know how i can do some antialiasing for edges that smooth these ty for reading and sry for my bad english |
12 | Learning Web Development and Game Development at the same time? I'm a junior level developer, currently working full time and trying to get experience with working with ASP.NET MVC. I love web development, and want to continue to pursue it as my career, but I also love gaming and have done a few game tutorials with Monogame XNA, and love that as well. For anyone that has been in this situation, Can you tell me, from experience, if you noticed any form of degenerative results when trying to split focus between a full time career in another field and beginning game development? I am looking for concrete examples of people who managed to split their time, and what their experience was like. I'm concerned that if I focus on game development on my spare time, then my growth in web development might suffer. I hope to use your input to determine for myself, how I should split up my free time, and manage my "Extracurricular" web projects, AND game development projects, so that I don't end up as a jack of all trades, master of none. I don't know why this is such a hard decision for me. ( |
12 | (XNA) Possible to hide, compress, or rename .XNB files? I'm fairly new to XNA (only a week into C and XNA at this point) but I have been developing games for a while now, and the program I used did not require any many external files in creating an executable. I am perfectly fine with external files (for the most part) but reading around, it seems as if .XNB files are easily accessed for others to pull your resources out of. After some thinking, I was wondering if it was possible to do any of these 3 things 1. Hide the .XNB files within the .exe in which case it would likely create them in an external location only during run time (wouldn't really solve the main issue, but still)? 2. Compress many of the .XNB binaries into a single binary (such as 1 for sounds, 1 for sprites, etc.) 3. (This one is one simply for my own OCD) Change the extension name from .XNB to something of my choosing? For example, to .DAT instead to make it less of a direct indicator I used XNA and or these files can be accessed with an .XNB ripper? None of these would particularly solve my initial problem, but I still wonder if they are possible. Anyhow, thanks in advance guys! |
12 | How to make my simple round sprite look right in XNA Ok, I'm very new to graphics programming (but not new to coding). I'm trying to load a simple image in XNA which I can do fine. It is a simple round circle which I made in photoshop. The problem is the edges show up rough when I draw it on the screen even with the exact size. The anti aliasing is missing. I'm sure I'm missing something very simple GraphicsDevice.Clear(Color.Black) TODO Add your drawing code here spriteBatch.Begin() spriteBatch.Draw(circle, new Rectangle(10, 10, 10, 10), Color.White) spriteBatch.End() Couldn't post picture because I'm a first time poster. But my smooth png circle has rough edges. So I found that if I added spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.NonPremultiplied) I can get a smooth image when the image is the same size as the original png. But if I want to scale that image up or down then the rough edges return. How do I get XNA to smoothly resize my simple round image to a smaller size without getting the rough edges? |
12 | Multi texturing in XNA I am attempting to make a map editor for my game, just so I can visualize how the end result would be. To my world I can add cubes (2 triangles) or corners (1 triangle), which are then added to a list of the vertices to draw, and the indices are added to a list of indices. Everything draws fine here, and I can set different colours for each vertex. I would like to implement texturing, so that when you add a primitive to the scene it will let you choose a texture (that, I can handle), but then also blend with other primitive's of different textures if they are touching (everything is on a grid). I would guess that I would have to store the texture name for each primitive, and somehow set that texture when drawing it. But I fail to see how you can set the effects texture when you are using one DrawUserIndexedPrimitives lt gt to draw the entire scene. If anyone has a work around for this, or ideas on other ways of doing this, you help would be greatly appreciated. Edit 1 I have incorporated the technique from this website here http toyfactorygame.com wp.php 2010 05 06 simple fast gpu driven multi textured terrain (similar to Blau's answer below), and have the current working result... Which maps to this... Using each color channel as a texture.. Output tex2D(TextureSampler0, input.TexCoords) input.Color.r Output tex2D(TextureSampler1, input.TexCoords) input.Color.g Output tex2D(TextureSampler2, input.TexCoords) input.Color.b Output tex2D(TextureSampler3, input.TexCoords) input.Color.a But doing it this way means I can only be setting 4 textures to blend together each DrawPrimitives call. Is there another way I can achieve multi texturing with more than 4 (preferably unlimited) textures? I know this is possible, as games like C amp C generals allow you to set textures anywhere you want on the map. Thanks. Twitchy |
12 | Flip sprite vertically AND horizontally? In Microsoft.Xna.Framework.Graphics.SpriteEffects there is the possibility to flip a texture horizontally or vertically before rendering. But can one do both at the same time? When I use spriteEffect SpriteEffects.FlipHorizontally SpriteEffects.FlipVertically with spriteEffect being a parameter of the particle. The method spriteBatch.Draw(spriteSheet, currentPositionForDraw, sourceRectangle, currentColorMultiplied, currentRotation, currentOriginForDraw, Temp.delta, spriteEffect, 0) does not draw the particle flipped on both axis. |
12 | Extrapolating performance on cheaper devices I am in the final stages of developing a game with XNA and MonoGame and am planning to release it on Windows Phone and Android. I personally have a Blu Win HD LTE and my father and sister have a Nexus 5 and Moto e, respectively. I am testing on all of these devices. What I am unsure of is how to extrapolate what the performance will be on cheaper devices, like a Lumia 630. I already can use profiling on my phone to make sure I'm under the 185MB memory limit, but I'm not sure what the framerate performance will be. I am looking for a way to roughly estimate how much slower the performance will be based on some variable (processor speed, GPU model, number of cores, etc.), such that I can tune performance on my current device and be assured of performance on cheaper devices. Has anyone tried this? |
12 | From camera coordinates to world coordinates I want to calculate world coordinates from camera coordinates. However, I seem to have problems with my understandings of how matrices in HLSL work. From world to camera is clear cameraPosition mul(mul(worldPosition, view), projection) Logic would now say that for the reverse, I could just use something like worldPosition mul(mul(cameraPosition, invProjection), invView) However, when I check if it is correct with cameraPosition mul(mul(mul(mul(cameraPosition, invProjection), invView), view), projection) I don't get the same point back anymore. The inverses should be fine as view invView produces the identity matrix etc. What is my misunderstanding here? Even the simpler case does not work void VS test(in float4 inPosition POSITION, out float4 outPosition POSITION) outPosition inPosition produces the triangle I want. However, using void VS test(in float4 inPosition POSITION, out float4 outPosition POSITION) outPosition mul(mul(inPosition, view), invView) already produces no visible triangle. Same with void VS test(in float4 inPosition POSITION, out float4 outPosition POSITION) outPosition mul(inPosition, mul(view, invView)) Pixel shader is just a shader which returns a constant color. UPDATE I have 3D camera space coordinates WITH z buffer value, like (0, 0, zNear) for the point directly in the center of the screen. I want to know what world coordinates correspond to this by doing the whole view transform backwards. |
12 | How to "swing" bounding box and update collision for sprite swinging a weapon? I have a simple question about sprite swinging weapons. I am making an RPG and would like something other than stabby swords, so why not swinging swords? I have a bounding rectangle for them, and the player equips them. Great, but I cannot grasp around my head how to swing both the sprite AND the bounding box (in XNA). The sprite is easy, I specify it's origin and rotate by a specified amount over a certain amount of time (the swing time), but the bounding rectangle poses another issue for me. Edit A bit of clarity on my swinging animation. It's basically the player holding out their arm and the weapon swings in a curve from about 45 degree angle to a 45 degree angle. |
12 | A Sensor s ContactList Keeps Old Ignores New Contacts, When That Contact Is still Okay this is a hard one to explain so I ll try my best. Basically every time my enemy class updates, it runs a SightCone Sensor Contact List test, so this is every single frame it checks for all the possible contacts in it s sensor. What I m finding is that if I m moving my player character around, the contact list updates perfectly, when the player is in the enemy s sight, it s true, when it is out of sight its false, However if I keep my player still, The contact list always ignores it. Here is a video showing the behaviour. (the true and false flag is in the top left.) Here is the code I have. Basically in the Enemy s update method I run the check (the sightcone is a supplemental body within the enemy class that follows the position and rotation of the enemy body every frame.) List lt Body gt coneClip GetBodiesInContactWithBody(SightCone.Body) private List lt Body gt GetBodiesInContactWithBody(Body body) var bodiesInContact new List lt Body gt () var c body.ContactList while (c ! null amp amp c.Next ! null) if (c.Contact.IsTouching) bodiesInContact.Add(c.Other) c c.Next return bodiesInContact I am not sure why this is happening. I don t know why the contact list isn t seeing the player, even though the body is still, it still exists, has a shape and position, and 100 exists in the physics world. Truly hope you can help. |
12 | Inconsistent accessibility error in xna Hey all, you may remember me asking a question regarding a snake game I was creating about two weeks ago. Well I'm quite far now into making the game (thanks to a brilliant tutorial I found). But I've come across the error described named above. So heres my problem I have a SnakeFood class that has a method called "Reposition". In the game1 class I have a method called "UpdateInGame" which calls the reposition method to load an orange that spawns in a random place every second. My latest piece of code changed the reposition method to allow the snake I have on the screen to not be overlapped by the orange that randomly spawns. Now I get the error (in full) Error 1 Inconsistent accessibility parameter type 'TheMathsSnakeGame.Snake' is less accessible than method 'TheMathsSnakeGame.SnakeFood.Reposition(TheMathsSnakeGame.Snake)' C Users Tom Documents Visual Studio 2008 Projects TheMathsSnakeGame TheMathsSnakeGame SnakeFood.cs 33 21 TheMathsSnakeGame I understand what the errors trying to tell me but having changed the accessiblity of the methods, I still can't get it to work. Sorry about the longwinded question. Thanks in advance ) Edit Code I'm using (Game1 Class) private void UpdateInGame(GameTime gameTime) Calls the oranges "reposition" method every second if (gameTime.TotalGameTime.Milliseconds 1000 0) orange.Reposition(sidney) sidney.Update(gameTime) (SnakeFood Class) public void Reposition(Snake snake) do position new Point(rand.Next(Grid.maxHeight), rand.Next(Grid.maxWidth)) while (snake.IsBodyOnPoint(position)) |
12 | How to design a GUI controls system classes I'm at the stage when I need to develop some kind of GUI with windows, clickable buttons, etc. It's going to be a RPG game so these components will be used extensively so I want them to be as flexible as possible. I was thinking about something like winform controls funcionality though much simpler, I don't think I'll need anything more than a window panel, button, label and image controls. So far I made abstract Component class which basic attributes like position, width height and two events mouseover and click. All controls will be derived from this base class. public abstract class Component public event EventHandler MouseOver public void OnMouseOver() if(MouseOver ! null) MouseOver(this, null) public event EventHandler Click public void OnClick() if (Click ! null) Click(this, null) private Rectangle componentRectangle private bool isVisible My question is how to integrate my controls with the rest of the game, I was thinking about something like GUIManager class that would contain the list of controls and manage displaying them and firing events. I'll be calling the update method somewhere in the game loop. public class GUIManager private List lt Component gt componenets public void Update(Vector2 mouseLocation) foreach (Component component in componenets) if (component.IsVisible) mouse is over component if (component.ComponentRectangle.Contains((int)mouseLocation.X, (int)mouseLocation.Y)) component.OnMouseOver() Now lets say I want to show character's inventory screen. Is it a good way to just create the controls, add events and then them to GUIManager's controls list to take care of it? Or maybe you can suggest some entirely diffrent approach? |
12 | Do I need to create an HLSL in XNA to display textures without content pipeline I currently have a jpeg texture stored as a Color array in XNA as RGBA. I also have the vertices of a cube in OBJ format mapped to VertexPositionColor vertex buffer using the VertexBuffer and Indices of the GraphicsDevice class. The OBJ has my jpeg mapped as a UV texture. I think I have all the Texture Coordinates as well(not sure, the array has 24 Vector3D values). I'm not sure where to go from here. I'm not using the Content Pipeline for my cube model or its texture though I'm wiling to add a custom .fx file if i need to. I realize I will have to add info about texture coords and color to my VertexDeclaration but do i need to write a custom effects file in HLSL to display my textured cube model or is there another way? |
12 | XBOX Xna ! DirectX? I'm a bit confused. The question is when I'm developing a XNA game for Xbox (or Windows), is it possible to use DirectX (to make use of the GPU)? Or is everything getting calculated by the CPU? A quick Google search didn't gave any results of combining those two... |
12 | Designing the Update system (read very basic game engine) for an XNA game I am trying to determine the best way to implement the "update" system or engine for a simple XNA game. Description of situation I have a few classes, lets call them Player will be an array list collection of 1 4 local players Enemy will consist of all enemy characters in the given "zone" Future not implemented, may not be implemented for this game, but may be needed in future Future I'm trying to decide what the best way to manage this will be, I'm going back and forth between a couple options. First Approach In the Update() method of my game, write code like this void Update(GameTime gameTime) var ctlInput GetControllerInput() for(int i 0 i lt 4 i ) if(Player i ! null) Player i .Update(gameTime, ctlInput) for(int i 0 i lt Enemy.Count i ) Enemy i .Update(gameTime, Player) In this version, I would add "FrameStatus" fields to the Player class, which would look like bool IsShooting and Vector2 TargetedLocation etc. This also means that each class would be responsible for knowing how to update itself in the game world. In my eyes, the advantages of this approach are No new classes. Classes become self documenting Easy to extend and add additional properties but the disadvantages are Order of code in Game.Update is very important Tight coupling of Player and Enemy classes Second Approach Implement a type of UpdateManager class, which accepts the user input, and it alone updates the Player and Enemy classes. This would relegate the Player and Enemy classes to simply dumb data classes, and they wouldn't necessarily have any game logic in them at all. void Update(GameTime gameTime) var ctlInput GetcontrollerInput() updateManager.Update(gameTime, ctlInput) The advantages of this approach, in my eyes, are Keeps code away from Game.Update() Doesn't require Player and Enemy classes to know about each other at all Disadvantages as I see it Adds a new class to my game The new class, will have a lot of code as time goes on and more types of objects enter the game world Actual Question Of the pro cons I've come up with for my two approaches, do you think I've missed any, what are they? which makes you lean for or against an approach, why? Which approach would you take, and also why would you go that route? Would you elect for a third option? What would that option look like? |
12 | Curved movement between two points What is a good technique to enable an object to move between to points in a nice curved motion? The end position could also be in motion, such as the trajectory of a homing missile. |
12 | XNA Distortion Shader problem So I came up with a distortion pixel shader in hlsl, but it has some issues. First of all, here is how it works The shader uses another texture generated by the program as a distortion "map" (if that's the correct term) I called this map a "mask". The shader uses the red values in the mask for horizontal distortion and the blue values as vertical distortion. The green values are not used. It subtracts 0.5 from the red and green values so that they have a range from 0.5 to 0.5 instead of 0 to 1. This lets the distortion go in any direction using only two color values. I let the shader "push" pixels up to 128 pixels. sampler s0 texture textu sampler tex sampler sampler state Texture textu float2 screenSize float4 PixelShaderFunction(float2 coords TEXCOORD0) COLOR0 float4 tex color tex2D(tex sampler, coords) if (tex color.a) float distX (tex color.r 0.5f) (256.0f screenSize.x) tex color.a float distY (tex color.b 0.5f) (256.0f screenSize.y) tex color.a return tex2D(s0, float2(coords.x distX, coords.y distY)) return tex2D(s0, coords) technique Technique1 pass Pass1 PixelShader compile ps 2 0 PixelShaderFunction() "textu" being the mask, "tex color" is the color value from the mask. It also multiplies the distortion by the alpha value in the mask. This seemed to work perfectly at first, but I started noticing some issues. I was using a completely white texture (as the mask) that was blurred around the edges. I set the color of this texture based on its rotation. Here is the method I used for that private Color GetDirectionColor(float rad) Vector2 v new Vector2( (float)Math.Cos(rad Math.PI), (float)Math.Sin(rad Math.PI) ) float r (v.X 0.5f) 0.5f float b (v.Y 0.5f) 0.5f return new Color(new Vector3(r, 0, b)) This allows the texture to "push" pixels in whatever direction it is facing. This method seems to work fine. The problem is, when the texture is rotated more than 135 degrees and less than 315 degrees (as in, the texture is pointing into the upper left half of a circle if you cut it in half at a 45 degree angle) it does something strange. Where the texture is blurred (the alpha values become less than 1) it starts to "push" the pixels in the opposite direction that it should be. I suspect this has to do with my shader and not something else in the program. Possibly the 0.5f part??? I'm terribly sorry if this is confusing... I could not find a better way to word it. Thanks a lot for your help! |
12 | Simulate movement towards the screen in a 2D world I need to create the illusion of someone kicking a ball to the screen. For that, I have a initial position of the ball (about the middle of the screen), and I put the sprite of the ball scaled at 0.2 of his original size. Then, I generate a random position on the screen, and move the ball sprite to it, and at the same time, I increment the scale of the ball, until I reach 1, the real size. At this point, the ball "hit" the screen. All this works great, but the scale of the ball is not coordinated with the movement of the ball, and, because of it, I must always wait until the scale reaches zero, after the ball is arrived to his destination, or, I must wait until the ball reach his destination, after the ball is already scaled to 1. The question is, how must I calculate the resize factor of the ball, so it gets to 1 at the same time that the ball reach the desirable coordinates in the screen? The speed of the ball is a random number between a given range, and, of course, I'm using only 2D sprites. |
12 | What kind of culling does XNA do for me? Which kinds of culling and clipping does XNA do for me as default, and which kinds does it not? Z culling? Backface culling? etc. |
12 | What can I do with an old XNA game? I have this little amusing game that I made in my second year of high school, and I'm rather impressed with it. It isn't anything that I could present in any style of major game conference or anything, it is simply a castle defense I enjoyed creating greatly that got me through my programming course with highest grades. It is simply too small to do anything big with, I made the majority of it in a single week Easter holiday, but I still want to share it. It was made in C , Visual Studio 2008, XNA 3.1. It can be played by either Xbox controller connected to the computer, or by keyboard. It relies heavily on XNA codes, I only thought of making things work so I saw it and not for everyone else. Now, my question. If I want to share it, is this possible, where do I do it, and what should I expect for incidents? I am entirely new to the concept of sharing my game online, so I don't even know where to start. Is the game simply too old? Is there someplace similar to, like, Newgrounds except for XNA games? What could I possibly release the game for? This kind of question must arise all the time, so I don't mind if I'm linked to some other question I've been unable to locate. All questions I've been able to find are asked before the people have even started the project, which is possibly smart. Me, I'm already done with this game and I'm wondering what I can do with it. Anyone who can sate my curiosity? |
12 | XNA Rendering Blocks I am currently building a little game in XNA and found something strange. I want to draw many blocks next to another (1x1x1 with a texture on the side) So what happens when I do it this lines appear When I move the camera the lines change the position or disappear completely. I know this is because the side of the blocks are drawn but i do not know why. Does anybody of you know a solution for my problem? (removing the sides of the cube does not count) |
12 | When to Dispose Textures I recently realized Texture2D implements IDisposable, and now (while trying to track down a memory leak) wonder about where and when I should dipose this. My current architecture is that I have a SpriteComponent instance which encapsulates and hides the Texture2D. Internally, when I switch screens (eg. MainMenuScreen WorldMapScreen), I call Dispose on the current screen, which calls dispose on the entities, which calls dispose on the textures. But this results in some wacked out behaviour, like textures apprearing super zoomed in momentarily, or appearing black, or appearing as garbage image data. So my question is really, when should I call Dispose on Texture2Ds? (FYI, I also can switch to a screen, and then later switch back to it, which currently causes me to reload the sprites, and by proxy, the textures.) |
12 | How to handle multiple effect files in XNA So I'm using ModelMesh and it's built in Effects parameter to draw a mesh with some shaders I'm playing with. I have a simple GUI that lets me change these parameters to my heart's desire. My question is, how do I handle shaders that have unique parameters? For example, I want a 'shiny' parameter that affects shaders with Phong type specular components, but for an environment mapping shader such a parameter doesn't make a lot of sense. How I have it right now is that every time I call the ModelMesh's Draw() function, I set all the Effect parameters as so foreach (ModelMesh m in model.Meshes) if (isDrawBunny true) Slightly change the way the world matrix is calculated if using the bunny object, since it is not quite centered in object space world boneTransforms m.ParentBone.Index Matrix.CreateScale(scale) rotation Matrix.CreateTranslation(position bunnyPositionTransform) else If not rendering the bunny, draw normally world boneTransforms m.ParentBone.Index Matrix.CreateScale(scale) rotation Matrix.CreateTranslation(position) foreach (Effect e in m.Effects) Matrix ViewProjection camera.ViewMatrix camera.ProjectionMatrix e.Parameters "ViewProjection" .SetValue(ViewProjection) e.Parameters "World" .SetValue(world) e.Parameters "diffuseLightPosition" .SetValue(lightPositionW) e.Parameters "CameraPosition" .SetValue(camera.Position) e.Parameters "LightColor" .SetValue(lightColor) e.Parameters "MaterialColor" .SetValue(materialColor) e.Parameters "shininess" .SetValue(shininess) e.Parameters e.Parameters "normal" m.Draw() Note the prescience of the example! The solutions I've thought of involve preloading all the shaders, and updating the unique parameters as needed. So my question is, is there a best practice I'm missing here? Is there a way to pull the parameters a given Effect needs from that Effect? Thank you all for your time! |
12 | Does the ClientSizeChanged event disable exceptions? If I illegally index into a list in the subscribed ClientSizeChanged() method, no ArgumentOutOfRangeException is thrown. Is this normal behavior ? And if so, when should I expect this behaviour ? Roy T. You're right in that it is an event which I'm subscribing to as follows game.Window.ClientSizeChanged new EventHandler lt EventArgs gt (Window ClientSizeChanged) and here's my event handler addendum (sorry, I don't know how to properly talk about these things) Event manager that responds to the window size being changed private static void Window ClientSizeChanged(object sender, EventArgs e) presentationRegion GDM.GraphicsDevice.PresentationParameters.Bounds if (currentScreen lt 0 currentScreen gt screens.Count) throw new Exception("currentScreen index is out of bounds of the screen list") List lt int gt myIntList new List lt int gt () myIntList 2 7 Exception is not thrown here screens currentScreen 1 .UpdateLayout() Game.Window.Title " WinCSC " I've put in the integer List just to demonstrate the effect. Although I originally noticed it with the screens currentScreen 1 .UpdateLayout() call. Blecki You are onto it I think. So when I trace the execution, as soon as i index into myIntList with an index of 2 execution breaks out of Window ClientSizeChanged() and the exception is not caught. And even if I throw my own exception inside Window ClientSizeChanged() the application continues without the debugger catching it. |
12 | Windows 7 8 imcompatibility via XNA? I have MS Visual Studio 2010 installed on my machine (a Windows 7 Pro 64 bit), and im developing a game in XNA 4.0 with it. I can run the program just fine from the .exe file in the bin directory, and it appears to have no bugs. But when trying it on Windows 8 64 bit, it just doesn't run. Am I doing something wrong or is XNA suddenly incompatible in this case? BTW this game has no 3d graphics at all, just 2D stuff, but iirc every texture2D is rendered through the GPU thing as some sort of flat 3D surface, so idk. |
12 | Stuck in Wall after rectangle bounding box collision Using XNA's built in Intersects() on two Rectangles, I can detect a collision and set my velocity to zero. However, the object is stuck there and can't get out! How can I resolve this collision properly? |
12 | XNA Framework Reach profile does not support separate alpha blend Yesterday I released my app 'Pic Words' to the windows phone store. It is an Silverlight XNA app that runs on Windows Phone 7.1 amp 8. I have BugSense incorporated into my app. Today I started receiving a lot of crash reports emanating exclusively from the 8.0.10211.0 version of Windows Phone 8. I could not replicate the issue since I do now currently own a Windows 8 phone and the emulator is running OS version 8.0.9903.0, which I don't think can be changed. The error from BugSense is as follows XNA Framework Reach profile does not support separate alpha blend. BlendState.ColorDestinationBlend and AlphaDestinationBlend must be set to the same value. Stack Trace at Microsoft.Xna.Framework.Graphics.ProfileCapabilities.ThrowNotSupportedException(String message, Object arg1, Object arg2) at Microsoft.Xna.Framework.Graphics.BlendState.Bind(GraphicsDevice device) at Microsoft.Xna.Framework.Graphics.GraphicsDevice.set BlendState(BlendState value) at Microsoft.Xna.Framework.Graphics.SpriteBatch.SetRenderState() at Microsoft.Xna.Framework.Graphics.SpriteBatch.End() at GlobalEngine.Base.SpriteBatchManager.ResumeSpriteBatch() at GlobalEngine.Base.SpriteBatchManager.Begin(SpriteBatchParams spriteBatchParams) at GlobalEngine.Base.SpriteBatchManager.Begin(Rectangle scissorArea) at GlobalEngine.Base.SpriteBatchManager.Begin() at FourWords.Screens.GameScreen.Draw(Color tint) at GlobalEngine.ScreenUtils.ScreenManager.Draw(Color tint) at GlobalEngine.Base.Engine.Draw() at FourWords.GamePage.OnDraw(Object sender, GameTimerEventArgs e) at Microsoft.Xna.Framework.GameTimer.RaiseDraw(GameTimerEventArgs gameArgs) at Microsoft.Xna.Framework.GameDispatcher.RunFrame() at Microsoft.Xna.Framework.GameDispatcher.OnTick(Object sender, EventArgs e) at MS.Internal.DirectRendering.OnGameUpdate(Object sender, EventArgs e) at MS.Internal.JoltHelper.RaiseEvent(IntPtr target, UInt32 eventId, IntPtr coreEventArgs, UInt32 eventArgsTypeIndex) GlobalEngine is just my library of basic classes like screen management and so on. SpriteBatchManager is a class I created also for managing the spritebatch. I Begin the spriteBatch with the following parameters SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None Additionally, I manipulate the graphic device as follows in the GamePage.xaml protected override void OnNavigatedTo(NavigationEventArgs e) Set the sharing mode of the graphics device to turn on XNA rendering SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true) SharedGraphicsDeviceManager.Current.PreferredBackBufferFormat SurfaceFormat.Color SharedGraphicsDeviceManager.Current.ApplyChanges() other unrelated code.... I could not find any help from searching online about this issue and would appreciate any advice on fixing it. Thanks. |
12 | Why does my collision detection code cause my framerate to drop? I have this code foreach (CollisionTiles tile in map.CollisionTiles) player.CollisionBox(tile) foreach (Enemy enemy in enemys) enemy.CollisionBox(tile) This is the CollisionBox() function public void CollisionBox(CollisionTiles tile) int x rectangle.X Map.Size int y rectangle.Y Map.Size int tileX (int)tile.Position.X int tileY (int)tile.Position.Y if (tileX gt x 1 amp amp tileX lt x 2 amp amp tileY gt y 1 amp amp tileY lt y 3) Collision(tile.Rectangle, Map.Width, Map.Height) tile.Collide true These two lines appear to be the problem int x rectangle.X Map.Size int y rectangle.Y Map.Size I guess because it loops through them on every tile... The Collision() function just check the face's of the two triangles (both player enemy and the tiles) with these functions public static bool TouchTopOf(this Rectangle r1, Rectangle r2) return (r1.Bottom gt r2.Top amp amp r1.Bottom lt r2.Top (r2.Height 2)) public static bool TouchBottomOf(this Rectangle r1, Rectangle r2) return (r1.Top gt r2.Bottom (r2.Height 2)) public static bool TouchLeftOf(this Rectangle r1, Rectangle r2) return (r1.Top lt r2.Bottom (r2.Height 2) amp amp r1.Bottom gt r2.Top (r2.Height 2) amp amp r1.Right gt r2.Left amp amp r1.Right lt r2.Left (r2.Width 4)) public static bool TouchRightOf(this Rectangle r1, Rectangle r2) return (r1.Top lt r2.Bottom (r2.Height 2) amp amp r1.Bottom gt r2.Top (r2.Height 2) amp amp r1.Left gt r2.Right (r2.Width 4) amp amp r1.Left lt r2.Right) When there is more then one monster with the player I get a massive FPSdrop, and it's getting worse when more monsters get added. What should I do to fix that problem? |
12 | SpriteBatch Draw Using Floats with the Destination Rectangle So I created a nice little isometric tile engine and I have it so that when you scroll with the mouse it changes a variable called scale. Scale is a float and gets passed through the spritebatch.draw() function. I apply scale to all of the math I do when generating the positions of the tiles. The problem I am having is Rectangle will not accept float numbers so when I make my Dest Rectangle for the spritebatch.draw() I can not use the numbers I need to because they are now floats. I tried using vector4 instead of rectangle but the spritebatch.draw was throwing an exception saying it was expecting Rectangle not Vector4. Is it possible to draw the dest rect using floats instead of ints? Btw the scale is all working properly however since I am casting the floats to ints any scale that should have a decimal gets truncated and I end up with spaces between my tiles. |
12 | How can I solve this SAT direct corner intersection edge case? I have a working SAT implementation, but I am running into a problem where direct collisions at a corner do not work for tiled surfaces. That is, it clips on the surface when going in a certain direction because it gets hung up on one of the tiles, and so, for example, if I walk across a floor while holding both down and left, the player will stop when meeting the next shape because the player will be colliding with the right side rather than with the top of the floor tile. This illustration shows what I mean The top block will translate right first and then up. I have checked here and here which are helpful, but this does not address what I should do in a situation where I don't have a tile based world. My usage of the term "tile" before isn't really accurate since what I'm doing here is manually placing square obstacles next to each other, not assigning them spots on a grid. What can I do to fix this? |
12 | How do I render into a sub region of a texture atlas with XNA HLSL? Is it possible to render into a texture atlas? I've been wondering how to reduce the number of textures required for shadow mapping, and came across a blog post here about rendering up to sixteen shadow maps into one texture atlas. According to the blog post mentioned above, these are the steps required 1. The first step is writing to the texture bind it to the framebuffer and set the viewport to render into the texture sub region. 2. When accessing the sub region, scale bias the texture coordinates as follows scale region size texture size, bias region offset texture size. I understand this, but I'm not sure how to alter the viewport specifically to allow me to render into a certain square of the texture. I've found plenty of information about reading from it (up sampling and down sampling) but I don't know how I'd manipulate the viewport specifically to render into a small square region of the screen, and how I'd do this with a texture smaller than the back buffer. I'm using XNA and HLSL at the moment because it's simpler than SharpDX, and there's no point in messing around with that until I've got the theory working 100 . Thanks for your help. |
12 | Smooth circular collisions with edges collision boxes C XNA So, me and a friend are working on our top down perspective 2D game, and have come to work on perfecting our collisions. In its current state our player sprite is colliding with walls, but is experiencing a "sticking" to the collided surface. This is mainly because our collisions only consist of "if colliding on X axsis, stop X movement" if (boxR.Intersects(playerCircle)) if (playerCircle.center.X lt boxR.X boxR.Width playerCircle.center.X gt boxR.X) stopX true if (playerCircle.center.Y lt boxR.Y boxR.Height playerCircle.center.Y gt boxR.Y) stopY true What we are intending is smoothed collisions, so that if we hold down the S key (for down), and the player's collision circle hits the corner of a collision rectangle, then the sprite's brute force of moving down pushes itself to the side to continue without further collision. Example below the solid line is the input vector, while the dotted line is the adjusted vector because of the collisions with the corner. Is there a seemingly simple adjustment to be made? Or will we need to incorporate some sort of physics library to get around this? If so, then what would you suggest? |
12 | Sweep collision between two moving spheres? Say I have a scenario like this Here I got two spheres (sphere A and B) that moves from on spot to another during a frame. How can I predict where these two collide if they collide at all? In between these frames? I tried to look it up and found this page, but I didn't understand much of it. Could someone try to explain this to me? I'm coding this in C with XNA and I've been stuck with this issue for a very long time now |
12 | Resolution independent game world in 3D I'm developing a game similar to Don't Starve 2D billboards in a 3D world. Now I have encountered a problem with resolutions. I want the player to be able to change resolution, but I don't want to change how much of the world that can be seen on screen. This is how it works in Don't Starve. So will the resolution just decide the size of the textures? Do I use a set internal resolution and then scale the textures according to the resolution? Do I then need to scale the world coordinates? I want the field of view to be the same and also so the camera angle(it's looking down with an angle as in most strategy games). I might also mention I'm coding with Monogame. |
12 | Should I go with SpriteBatch or just 3D with Z component always zero? I'm designing a platformer and beginning to code the viewing engine of the game. Now, I have to make a key decision Should I just use SpriteBatch to draw all the 2D stuff, as there is no 3D, or should I just go with making camera facing polygons with Z set to zero? What are the good sides and drawbacks of both? Performance? Extensibility? Performance is a key factor as I'll be having lots of texttures objects effects animations etc, and I'll be targetting high resolutions like 1920x1200 (if available on client's computer), so I need things to go smooth. On the other hand, I also need some extensibility, as I want to have great control over the drawing methods. Seems like I'd be going with 3D polygon method, but I was wondering if it has any side effects? |
12 | Incorrect frustum culling with center half size AABB I'm trying to implement an axis aligned bounding box with center half size instead of min max. And I have some problems when it comes to create a method to detect if the aabb is visible or not. I try to do the same as on this website at "Method 5" http fgiesen.wordpress.com 2010 10 17 view frustum culling . I'm trying to implement this formula return dot3(center extent signFlip, plane) plane.w But it doesn't work at all and I don't find what's going wrong. Objects in my scene seems to appear and disappear in a strange way, sometimes appears when I'm not watching them or disappears when frustum faces them (I look at draw calls to determine if the isVisible test returns true or false). Here is my code The Axis aligned bounding box public sealed class AxisAlignedBox public Vector3 Center public Vector3 HalfSize The method in the frustum that tests if the aabb is visible or not public bool Intersects(AxisAlignedBox aabb) Vector3 v float d Vector3.Multiply(ref aabb.HalfSize, ref signPlane 0 , out v) Vector3.Add(ref aabb.Center, ref v, out v) Vector3.Dot(ref v, ref planes 0 .Normal, out d) if (d gt planes 0 .D) return true Vector3.Multiply(ref aabb.HalfSize, ref signPlane 1 , out v) Vector3.Add(ref aabb.Center, ref v, out v) Vector3.Dot(ref v, ref planes 1 .Normal, out d) if (d gt planes 1 .D) return true Vector3.Multiply(ref aabb.HalfSize, ref signPlane 2 , out v) Vector3.Add(ref aabb.Center, ref v, out v) Vector3.Dot(ref v, ref planes 2 .Normal, out d) if (d gt planes 2 .D) return true Vector3.Multiply(ref aabb.HalfSize, ref signPlane 3 , out v) Vector3.Add(ref aabb.Center, ref v, out v) Vector3.Dot(ref v, ref planes 3 .Normal, out d) if (d gt planes 3 .D) return true Vector3.Multiply(ref aabb.HalfSize, ref signPlane 4 , out v) Vector3.Add(ref aabb.Center, ref v, out v) Vector3.Dot(ref v, ref planes 4 .Normal, out d) if (d gt planes 4 .D) return true Vector3.Multiply(ref aabb.HalfSize, ref signPlane 5 , out v) Vector3.Add(ref aabb.Center, ref v, out v) Vector3.Dot(ref v, ref planes 5 .Normal, out d) if (d gt planes 5 .D) return true return false signPlane is an array of Vector3 using the following formula and applied for each plane once per frame when the frustum is updated public static void Sign(ref Vector3 v, out Vector3 result) result.X Math.Sign(v.X) result.Y Math.Sign(v.Y) result.Z Math.Sign(v.Z) |
12 | Changing the position of a Gravity Controller Farseer I'm trying to create mini black holes for my XNA game using farseer physics. Problem is I can not get the gravity source to stick to the Body I've attached it to, as it scrolls across the screen, the gravity source simply stays in the same position. This is the code I've used. Body blackHoleBody blackHoleBody BodyFactory.CreateBody(world) CircleShape ballShape new CircleShape(ConvertUnits.ToSimUnits(imageItemList i .texture.Width 2f), 1f) Fixture ballFixture blackHoleBody.CreateFixture(ballShape) blackHoleBody.BodyType BodyType.Static blackHoleBody.Position ConvertUnits.ToSimUnits(imageItemList i .Position) blackHoleBody.Restitution 0.0f blackHoleBody.CollisionCategories Category.All blackHoleBody.CollidesWith Category.All Create the gravity controller GravityController gravity new GravityController(10f) gravity.DisabledOnGroup 3 gravity.EnabledOnGroup 2 gravity.DisabledOnCategories Category.Cat2 gravity.EnabledOnCategories Category.Cat3 gravity.GravityType GravityType.Linear world.AddController(gravity) gravity.AddBody(blackHoleBody) ballBodyList.Add(blackHoleBody) My guess is that I need to get in the GravityController inside world, and update it's position there, but when I look I can only find the world global gravity. If anyone could point me in the right direction it would be much appreciated. |
12 | XNA just a few more characters accepted in a SpriteFont I have a SpriteFont in XNA, which has the standard 126 characters that are usable. However i would like to use the " " symbol in the game. So is there anyway of adding just a few more symbols that the spritefont accepts? Cheers, Randomman159 |
12 | Primitives does not show on screen I'm trying to render terrain, everything compiles fine, but I can't see anything on screen. ( I'm moving camera around in case it was on the other side) Can't figure out whats wrong. public class Terrain public VertexBuffer vertexBuffer public IndexBuffer indexBuffer public VertexPositionNormalTexture vertices public int indices int gridSize Camera camera ContentManager Content GraphicsDevice device Texture2D heightmap public Texture2D grass Effect effect public Terrain(ContentManager Content, GraphicsDevice device, Camera camera) this.Content Content this.device device this.camera camera heightmap Content.Load lt Texture2D gt ("Gfx heightmap") grass Content.Load lt Texture2D gt ("Gfx grass") effect Content.Load lt Effect gt ("Effects terrain") CreateVertices() CreateIndices() public void Draw() effect.CurrentTechnique effect.Techniques "Texture1" effect.Parameters "xWorldViewProjection" .SetValue(camera.worldMatrix camera.viewMatrix camera.projMatrix) effect.Parameters "xTexture" .SetValue(grass) foreach (EffectPass pass in effect.CurrentTechnique.Passes) pass.Apply() device.DrawUserIndexedPrimitives lt VertexPositionNormalTexture gt (PrimitiveType.TriangleList, vertices, 0, vertices.Length, indices, 0, indices.Length 3) private void CreateVertices() vertices new VertexPositionNormalTexture heightmap.Width heightmap.Height for (int x 0 x lt heightmap.Width x ) for (int y 0 y lt heightmap.Height y ) vertices y heightmap.Width x .Position new Vector3(x, 0, y) vertices y heightmap.Width x .Normal new Vector3(0, 1, 0) vertices y heightmap.Width x .TextureCoordinate new Vector2(y, x) device.SetVertexBuffer(vertexBuffer) private void CreateIndices() indices new int (heightmap.Width 1) (heightmap.Height 1) 6 int counter 0 for (int x 0 x lt heightmap.Width 1 x ) for (int y 0 y lt heightmap.Height 1 y ) int lowerLeft x y heightmap.Width int lowerRight (x 1) y heightmap.Width int topLeft x (y 1) heightmap.Width int topRight (x 1) (y 1) heightmap.Width indices counter topLeft indices counter lowerRight indices counter lowerLeft indices counter topLeft indices counter topRight indices counter lowerRight |
12 | C XNA Elasticity Behavior What is elasticity? How do I implement such a thing? |
12 | Multiple ( V I ) Buffers, is it sane? Currently I am developing an RTS game using XNA ( ANX.Framework ). There is one thing bothers me. I am not sure in what way or how to organise Buffers. Should I use a new Vertexbuffer for any object ( e.g. a Char, a Table, an model ) or is it better to use ONE HUGE BIG Buffer to store any geometry in? I am still new to 3D Programming though I finished yet couple games using DirectX 9. Well, I hope this question qin't a duplicate and I appreciate any answer leading me into the right direction. |
12 | 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 | Creating Entities from Identifiers (C ) I am writing a game in C XNA. Often, it's useful to have a function like this in a game engine Entity CreateEntity(string id, Vector3 location) ... So that, for instance, you can do something like this List lt string gt entitiesToSpawn "Tree", "Bird", "Flower", ... foreach (string entity in entitiesToSpawn) CreateEntitiy(entity, location) Or else you can easily store the ids in data files, or populate generic GUI elements with them, for instance. What, in your opinion, is the best way to implement CreateEntity in such a way that is scalable and preserves this kind of interface? Right now, I have a gigantic static switch statement, which is obviously not sustainable. Perhaps I can create a big static map of strings to functions? Or is there an easier way to get this kind of functionality out of my engine? |
12 | Drawing transparent and opaque 3D objects. How do I preventing z fighting? I am using a transparent weighted average algorithm to draw my transparent objects. The transparent object is drawn with the following notable render states (the rest are default XNA values) CustomBlendState.Additive, DepthStencilState.DepthRead, RasterizerState.CullNone, SamplerState.PointClamp The opaque object is drawn using the following states BlendState.Opaque DepthStencilState.Default RasterizerState.CullCounterClockwise SamplerState.PointClamp In the picture below there is what I believe is a z fighting issue where the green block and the wooden block meet. How can I keep the objects in the same location and stop this issue from occurring? When changing the transparent object's DepthStencilState.DepthRead state to DepthStencilState.None the issue goes away. While this is what led me to believe it was a z fighting issue, the opaque object will then no longer occlude the transparent object when viewed from another angle. EDIT Applying a depth bias to the situation makes no discernible difference either public static RasterizerState SolidNoCullBias new RasterizerState() CullMode CullMode.None, FillMode FillMode.Solid, DepthBias 1f, SlopeScaleDepthBias 1f, EDIT 2 Culling the triangles will cause the object to look incorrect as a transparent object should show both the inside and outside faces. EDIT 3 Depth Stencil State is as follows with 'LessEqual' compare function (doesn't solve the issue) |
12 | C How to properly play background songs in XNA So I'm using the game states (enum) to change my game screens. I have 2 songs for main menu and game playing states, respectively. To play songs, I'm using an old code example I saw at MSDN, like this bool songStart false Song song1 Song song2 LoadContent method song1 Content.Load lt Song gt (". Songs mainMenuTheme") song2 Content.Load lt Song gt (". Songs mainGameTheme") MediaPlayer.IsRepeating true Update method switch (CurrentGameState) case gameState.mainMenu if (CurrentGameState gameState.mainMenu amp amp !songStart) MediaPlayer.Stop() MediaPlayer.Play(song) songStart true else if (CurrentGameState ! gameState.mainMenu amp amp songStart true) MediaPlayer.Stop() songStart false break case gameState.gamePlaying if (CurrentGameState gameState.gamePlaying amp amp !m SongStart) MediaPlayer.Stop() MediaPlayer.Play(song2) m SongStart true else if (CurrentGameState ! gameState.gamePlaying amp amp songStart true) MediaPlayer.Stop() songStart false break So if I am in mainMenu, the first song plays when I go to gamePalying the first song stops and the second one starts playing. If I return to mainMenu, the mainMenu song plays. My issue however, is that if I click Play game and the state moves to gamePlaying there is no background music! What could've caused the problem? Please help me fix it, I'm stuck for a whole week. |
12 | rendering a spritebatch to a temporary buffer and then offset that to the main screen I've been trying to figure out how to do this but I have a bunch of screens, each with their own Draw method. However, I'd like to render all sprites offset by the screen position without altering their locations before I do the drawing. So, if I render a sprite on a screen at 0,0 but the screen itself is offset to 50,50 it still renders to a window position of 0,0 instead of to the window position of 50,50. I've been thinking about rendering each screen to their own texture and then rendering that texture to the main spriteBatch but reading another question you could lose a lot of information such as alpha transparency Any help will be appreciated to get me on the right path. Thanks. Update Also I'd prefer it to be recursive so that screens within screens are also offset appropriately. |
12 | How to improve collision detection memory usage? I am making an action platform 2D game, something like Megaman. I am using XNA to make it. I already made player physics, collisions, bullets, enemies and AIs, map editor, scrolling X Y camera (about 75 of game is finished ). As I progressed I noticed that my game would be more interesting to play if bullets would be destroyed on collision with regular(stationary) map blocks, only problem is that if I use my collision detection (each bullet with each block) sometimes it begins to lag(btw if my bullet exits the screen player can see it is removed from bullet list) So how to improve my collision detection so that memory usage would be so high? ) ( on a map 300x300 blocks for example don't think that bigger map should be made) int block 0 int bulet 0 bool destroy bullet false while (bulet lt bullets.Count) while (block lt blocks.Count) if (bullets bulet .P Bul rec.Intersects( blocks block .rect)) bullets and block are Lists that holds objects of bullet and block classes P Bul rec just bullet rectangle destroy bullet true block if (destroy bullet) bullets.RemoveAt(bulet) destroy bullet false else bulet block 0 |
12 | SpriteBatch.Begin() making my model not render correctly I was trying to output some debug information using DrawString when I noticed my model suddenly was being rendered like it was inside out (like the culling had been disabled or something) and the texture maps weren't applied I commented out the DrawString method until I only had SpriteBatch.Begin() and .End() and that was enough to cause the model rendering corruption when I commented those calls out the model rendered correctly What could this be a symptom of? I've stripped it down to the barest of code to isolate the problem and this is what I noticed. Draw code below (as stripped down as possible) GraphicsDevice.Clear(Color.LightGray) foreach (ModelMesh mesh in TIEAdvanced.Meshes) foreach (Effect effect in mesh.Effects) if (effect is BasicEffect) ((BasicEffect)effect).EnableDefaultLighting() effect.CurrentTechnique.Passes 0 .Apply() spriteBatch.Begin() spriteBatch.DrawString(spriteFont, "Camera Position " cameraPosition.ToString(), new Vector2(10, 10), Color.Blue) spriteBatch.End() GraphicsDevice.DepthStencilState DepthStencilState.Default TIEAdvanced.Draw(Matrix.CreateScale(0.025f), viewMatrix, projectionMatrix) |
12 | Smallest increment for a SpriteBatch depth between 0.0 and 1.0? I experienced some problems with SpriteBatch in XNA when I tried to mix two different SpriteSort modes. (Begin with deferred, end, begin with BackToFront wasn't sorting properly.) I've settled on just giving everything I draw with SpriteBatch a depth value. To that end, what is the smallest increment I can use on the floating point variable that will be used as the depth parameter without running into rounding problems? The valid values for this float are between 0.0 and 1.0. It is a float, not a double, and the language is C . UPDATE My testing has shown that 0.008f is the smallest amount I can change my depth value by and be certain the sorting will work. I'm guessing there is something else at play in BasicEffect or SpriteBatch. What I am trying to use this for is the rendering of my game's map grid. I want to make heavy use of transparency and overlapping to create a specific visual look for the tiles, the doodads, and the characters. Essentially, I am using a painter's algorithm to draw the tiles in order from the back row to the front. I have them numbered so I know the ordering is correct. The doodads I am trying to draw on top of the map are not appearing when my depth decrementor is set to a low enough number to draw everything I will need. It only works properly in a range where I can only access about 100 unique depths. UPDATE about SpriteSortMode problems (as requested) Thus far in my project I have got by just fine using SpriteSortMode.Deferred for everything. I have all of the standard UI components you would expect, windowing, clipping, etc. working. Now I am attempting to draw my map grid. Like windowing clipping this requires things to be done in a specific order to look right. The grid tiles draw in a certain order. To accommodate overlapping, doodads characters draw on top of a tile before the next tile is drawn. No matter what I did, my doodads characters would always be drawn under the tiles. Changing the order of draws had no impact. Even drawing all of the tiles and then drawing the doodads resulted in them showing up underneath the tiles. Especially odd was that my UI elements continued to appear above the problem tiles as I scrolled around the map. I switched to SpriteSortMode.BackToFront and with a high enough depth difference ( 0.01) I see things drawing on the grid as expected, but this depth difference is way too high to support every visible tile of the map. I am searching for a better solution than to write code that will End and Begin a new SpriteBatch every time 100 pieces are drawn. |
12 | Trouble using Ray.Intersect method on bounding boxes in a 2D XNA game I am trying to use a ray and bounding box to determine if a box is between the player and the mouse pointer in 2D space. When I try testing the code, the collision will return true when pointed at the box but it also returns true under other circumstances where it shouldn't. For instance. If I have a player on the left and a box directly to the right, I can put the mouse pointer a few hundred pixels above the box or a few hundred below and it will still return true. Also, I can put my mouse pointer to the left of the player and in a certain area it will still return true. Does anyone have any idea what might cause this? I have left out definitions for some of my members and properties just to make this code sample easier to read. The position property is just a Vector2 for where each object is located. ray new Ray(new Vector3(player.Position, 0), new Vector3(mouse.Position, 0) box new BoundingBox(new Vector3(box.Position, 0), new Vector3( new Vector2(box.Position box.Width, box.Position box.Height), 0) if (ray.Intersects(box) ! null) collision true else collision false |
12 | 2D Grid based game how should I draw grid lines? I'm playing around with a 2D grid based game idea, and I am using sprites for the grid cells. Let's say there is a 10 x 10 grid and each cell is 48x48, which will have sprites drawn there. That is fine. But in design mode, I'd like to have a grid overlay the screen. I can do this either with sprites (2x600 pixel image etc) or with primitives, but which is best? Should I really be switching between sprites and 3d 2d rendering? Like so Thanks! |
12 | HLSL Shader Relative Positioning I've got a shader that does the texturing, lighting, etc. for my game engine (written on top of MonoGame, in case that's relevant) for my block terrain based game (everything is rendered as triangles and each chunk has its own mesh made from logical block objects, recomputed when relevant). I have two versions of this shader, a SM2 one and an SM4 one (for different targets), both do the same thing and are almost identical but I primarily focus on the SM2 one since that is for the primary target. Anyway, a week or so ago I implemented directional lighting, and it looks fine.. except it seems to fail to take the distance from the light source into account i.e., every block looks like it's an equal distance from the light source. I tried setting up some obvious solutions I was already calculating the direction of the light using a parameter of the light position with the vertex position, so I took an intermediate (pre normalization) value of this and used it as the distance to modulate the intensity of the light. Sounds good, yeah? Well, it somehow made no difference at all. I can't seem to find a piece of software to help me debug a vertex pixel shader combo (only lone pixel shaders), so I'm basically stuck thinking through the logic and trying things. That's a familiar debug style for me, but I've been trying for a week or two and haven't come up with anything that has made a difference. I've since stripped this out of the shader (since it didn't work, and I wanted to just work on other things for a while), but I was calculating the distance in the vertex shader (and passing it to the pixel shader) like this float3 final3DPos mul(inPos, World) float3 direction (final3DPos LightPosition) Output.LightDirection direction Output.LightDistance length(direction) I also tried setting LightDistance to (abs(distance.x) abs(distance.z)), with distance being what in the above is LightDistance I ignored Y since it's constant and figured it would exaggerate the difference between positions.. same effect! In the pixel shader, LightDirection is normalized before use. I tried setting the end result as a color made from the distance, and everything ended up black. I tried dividing this by various values in case the numbers were too big and multiplying by 255, and no matter what i did everything was the same color. I tried just using it in the calculations by dividing by it or deriving a multiplier to use from it, and again every block was lit the same. I could pass the distance to the light in with the vertex information, but calculating that and sending it in for EVERY VERTEX seems really stupid and unnecessary.. ( |
12 | How do you create a .XNB Font file for use with CocosSharp? I know the .XNB file format is an XNA thing and that CocosSharp inherits this from its MonoGame roots. However there doesn't seem to be any information on how to create your own .XNB fonts to use with CocosSharp. I've tried searching but can find any information. Could someone explain it here or point me to a tutorial on how to create .XNB font file for use with CocosSharp? A site to download already compiled .XNB Fonts would also be acceptable. Update Another thing that makes this tricky is that I guess XNA Game Studio could be used, but it's not compatible with Windows 8.1 which is what I currently use for my dev machine... |
12 | XNA 4.0 Purple Pink Tint Over All Sprites After Viewing in FullScreen I'm a noob to the game dev world and recently finished the 2D XNA tutorial from http www.pluralsight.com. Everything was perfect until I decided to try the game in Fullscreen mode. The following code was added to the Game1 constructor. graphics.PreferredBackBufferWidth 800 graphics.PreferredBackBufferHeight 480 graphics.IsFullScreen true As soon as it launched in Fullscreen, I noticed that the entire game was tinted. None of the colours were appearing as they should. That code was removed, the game then launched in the 800x480 window, however the tint remained. I commented out all my Draw code so that all that was left was GraphicsDevice.Clear(Color.CornflowerBlue) spriteBatch.Begin() gameState.Draw(spriteBatch, false) spriteBatch.End() spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive) gameState.Draw(spriteBatch, true) spriteBatch.End() base.Draw(gameTime) The result was an empty window that was tinted Purple, not Blue. I changed the GraphicsDevice.Clear colour to Color.White and the window was tinted Pink. Color.Transparent gave a Black window. Even tried rebooting my PC but the 'tint' still remains. I'm at a loss here. |
12 | How do I get bullets to move in the direction of the mouse's position? Possible Duplicate Shoot a bullet towards cursor top down 2d I'm creating a 2D top down shooter, and I want to get the bullets to go in the direction of the mouse. Not sure of the logic that goes into it. |
12 | Farseer physics engine The name 'ConvertUnits' does not exist in the current context http digitalerr0r.wordpress.com 2012 03 11 farseer physics in xna 4 0 for windows phone 1 I tried this Farseer tutorial but I always get that error message in the following lines spriteBatch.Draw(rectangleSprite, ConvertUnits.ToDisplayUnits(rectangle.Position), null, Color.White, rectangle.Rotation, new Vector2(rectangleSprite.Width 2.0f, rectangleSprite.Height 2.0f), 1f, SpriteEffects.None, 0f) spriteBatch.Draw(rectangleSprite, ConvertUnits.ToDisplayUnits(rectangle2.Position), null, Color.White, rectangle2.Rotation, new Vector2(rectangleSprite.Width 2.0f, rectangleSprite.Height 2.0f), 1f, SpriteEffects.None, 0f) spriteBatch.Draw(rectangleSprite, ConvertUnits.ToDisplayUnits(rectangle3.Position), null, Color.White, rectangle3.Rotation, new Vector2(rectangleSprite.Width 2.0f, rectangleSprite.Height 2.0f), 1f, SpriteEffects.None, 0f) What is wrong? I added the two usings to my code but I always get this error message The name 'ConvertUnits' does not exist in the current context |
12 | Facilitating XNA game deployments for non programmers I'm currently working on an RPG, using the RPG starter kit from XNA as a base. (http xbox.create.msdn.com en US education catalog sample roleplaying game) I'm working with a small team (two designers and one music sound artist), but I'm the only programmer. Currently, we're working with the following (unsustainable) system the team creates new pics sounds to add to the game, or they modify existing sounds pics, then they commit their work to a repository, where we keep a current build of everything. (Code, images, sound, etc.) Every day or so, I create a new installer, reflecting the new images, code changes, and sound, and everyone installs it. My issue is this I want to create a system where the rest of the team can replace the combat sounds, for instance, and they can immediately see the changes, without having to wait for me to build. The way XNA's setup, if I publish, it encodes all of the image and sound files, so the team can't "hot swap." I can set up Microsoft VS on everyone's machine and show them how to quickly publish, but I wanted to know if there was a simpler way of doing this. Has anyone come up against this when working with teams using XNA? |
12 | Creating a collision shape for a complex model I'm currently creating the collision system for my 3D XNA game. To check collisions with models (especially complex ones) like trees or other plants, I thought about rendering a low poly version of this object and check if the player is in collision with that low poly shape. I succeeded in getting all the positions of all vertices in my models. If my model is a cube, I get the 8 vertices, but how can I check if the player is inside this shape? |
12 | Best practices in managing character states While in development of a character, I feel like I'm digging myself deeper into a hole every time I add more functionality to him, creating more bugs and it seems like my code is tripping over itself all over the place. What are the best practices when managing character states for a character that has a large selection of abilities and actions that they can perform, without their abilities interrupting each other and creating a mess overall? |
12 | How do I create a 3rd person camera? I currently have a camera class set up and have my model player loaded but I can't get my camera in the correct position by changing the x,y,z coordinates. I have set up my "game" with a separate class for the model player and a class for the camera. I am fairly new to XNA and most of what I have already got is from a tutorial from my lecturer. Here is my player model class public class Player public Model model public Matrix world Matrix.Identity public Vector3 position public Vector3 direction public Quaternion rotation Quaternion.Identity public BoundingSphere collision public float speed 2f public float moveForwards public float moveLeft public float forward Matrix transform public Player(Model m, Vector3 iPos) model m position iPos direction new Vector3(0, 0, 1) transform new Matrix m.Bones.Count m.CopyAbsoluteBoneTransformsTo(transform) foreach (ModelMesh mesh in m.Meshes) collision BoundingSphere.CreateMerged(collision, mesh.BoundingSphere) public Player() public BoundingSphere getSphere() return collision.Transform(world) public void sampleInputMovement(GamePadState player) moveForwards (player.ThumbSticks.Left.Y 5) moveLeft (player.ThumbSticks.Left.X 32) 1 public void update() rotation Quaternion.CreateFromAxisAngle(new Vector3(0, 0, 1), moveLeft) Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), moveForwards) Vector3 motion Vector3.Transform(direction, rotation) position motion forward world Matrix.CreateFromQuaternion(rotation) Matrix.CreateTranslation(position) public void Draw(Matrix projection, Matrix view) Matrix transforms new Matrix model.Bones.Count model.CopyAbsoluteBoneTransformsTo(transforms) foreach (ModelMesh mesh in model.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.EnableDefaultLighting() effect.Projection projection effect.View view effect.World transforms mesh.ParentBone.Index world mesh.Draw() And here is my camera class public class Camera Vector3 position Vector3 newposition Quaternion cameraRotation Vector3 targetOffset new Vector3(0, 1f, 6f) public Matrix view Matrix.Identity public Matrix projection Matrix.Identity public Camera(Game game, Vector3 xPostion) position xPostion projection Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, game.GraphicsDevice.Viewport.AspectRatio, 1.0f, 1000000f) public void update(Matrix targetWorld) Quaternion rotation Vector3 target Vector3 scale targetWorld.Decompose(out scale, out rotation, out target) cameraRotation Quaternion.Lerp(cameraRotation, rotation, 0.15f) newposition Vector3.Transform(targetOffset, targetWorld) position Vector3.SmoothStep(position, newposition, 0.8f) Vector3 cameraup Vector3.Transform(new Vector3(0, 1, 0), Matrix.CreateFromQuaternion(cameraRotation)) view Matrix.CreateLookAt(position, target, cameraup) Could someone help me get my camera in the correct position? |
12 | XNA 2D How to load unload specific content by level I'm writing a 2D room based platformer using XNA, and I'm trying to figure out the best way to load resources based on what the current map requires. Basically, I need to (want to) dispose of the loaded tileset textures and load just the ones the next map requests at every transition (ideally, I'll check if they're actually different first), without killing off the more universal textures (player sprites, etc.). I've seen a few forum posts saying the best way to do this is to create a second instance of ContentManager, but they never go into detail on how to do this correctly. Currently, my XML map files each contain strings with the filenames of all necessary assets. I was planning on having my XmlReader method load the textures as their names were read, but then I realized I knew neither how to instantiate the second ContentManager, nor where to instantiate it i.e., should it be in the MapFactory class that's loading the map, or in the static LevelManager that's calling the MapFactory (passing the new ContentManager as a parameter to the MapFactory, along with the name of the desired map)? Alternatively, is there a simpler cleaner way to do this? I'm more concerned with the code being easily comprehensible than efficient right now, as this is my first attempt at this kind of game. Ex. Castlevania, Metroid, but simpler (for now). I'd like to implement constant streaming eventually (chunks loaded as they are approached), but I want to get this part down first. UPDATE Instantiated the second ContentManager using this.Services inside the Game class (it was the only way I could find to get access to Game.Services, which is what everywhere online says to use in the ContentManager constructor). Should have thought of that sooner. For anyone confused by this in the future, the full line of code is ContentManager myContent new ContentManager(this.Services, "myContent") |
12 | drawing meshes so that they respect the position in space (doesn't draw on top of another mesh if behind it) How can i make my meshes be drawn taking in account which one is in from of another? i.e. if i have a mesh that is farder than another it should be drawn behind the second. Is there a way to do this in xna that is more standardized or do i have to calculate for each mesh myself? If i have to calculate for each mesh by myself, from which point do i calculate the distance to the mesh? the camera position? Here is how i draw them Matrix transforms new Matrix gameobject.model.Bones.Count gameobject.model.CopyAbsoluteBoneTransformsTo(transforms) foreach (ModelMesh mesh in gameobject.model.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.Projection camera.projectionMatrix effect.View camera.viewMatrix effect.World transforms mesh.ParentBone.Index gameobject.orientation mesh.Draw() |
12 | Windows Class Library vs XNA Class Library I'm going to start a library in C for Navigational Meshes. I would like to use it in both WPF Winforms and in XNA. Can I create a windows class library and still use it in XNA? |
12 | Implementing a 2d Selection Box I'm in the process of implementing a selection box for my simulation and am having difficulty with something which appears simple. At the moment, I can draw the selection box and accurately select the items under it, provided the box was dragged from the top left hand corner downwards If I start dragging the box from any other point the rectangle doesn't correspond to that of the viewport, as demonstrated by the negative width and height. Here is my code selectionBox is Rectangle if (mouse.LeftButton ButtonState.Pressed amp amp prevMouse.LeftButton ButtonState.Pressed) if (selecting) selectionBox.Width mouse.X selectionBox.X selectionBox.Height mouse.Y selectionBox.Y else selecting true selectionBox.X mouse.X selectionBox.Y mouse.Y Code to handle selection finished omitted Drawing code if (selecting) DrawingHelper.DrawRectangle(selectionBox, Color.Yellow, false) DrawingHelper.DrawRectangle(new Rectangle(startPoint.X 4, startPoint.Y 4, 8, 8), Color.Red, true) How can I adjust the X, Y, Width and Height of my selection box so that X and Y are always the top left of the selection box no matter where the selection began? |
12 | Error on MonoGame Content Pipeline Texture Importer Error I just encountered this kind of error when using the MonoGame Content Pipeline and it's my first time to use it to convert png to xnb files (I use a stand alone app for converting files to xnb in the past). I've done building spritefonts to xnb files and stuff like that in my previous MonoGame projects and I thought it would be similar but it turned out to be not the case. So this is the error I have error Importer 'TextureImporter' had unexpected failure! System.NullReferenceException Object reference not set to an instance of an object at Microsoft.Xna.Framework.Content.Pipeline.TextureImporter.Import (System.String filename, Microsoft.Xna.Framework.Content.Pipeline.ContentImporterContext context) 0x00000 in lt filename unknown gt 0 at Microsoft.Xna.Framework.Content.Pipeline.ContentImporter 1 Microsoft.Xna.Framework.Content.Pipeline.Graphics.TextureContent .Microsoft.Xna.Framework.Content.Pipeline.IContentImporter.Import (System.String filename, Microsoft.Xna.Framework.Content.Pipeline.ContentImporterContext context) 0x00000 in lt filename unknown gt 0 at MonoGame.Framework.Content.Pipeline.Builder.PipelineManager.ProcessContent (MonoGame.Framework.Content.Pipeline.Builder.PipelineBuildEvent pipelineEvent) 0x00000 in lt filename unknown gt 0 Is there a way to resolve this? Is there a tutorial of some kind I can follow to use the TextureImporter and the things I haven't yet understood on MonoGame's Content Pipeline with in depth explanation about it? |
12 | XNA HLSL rendering a model with its original materials (colors) I am currently trying to code my own HLSL effect file, in order to render an FBX model I made with Autodesk maya, and to which I have applied some materials (colors). before trying to write an effect file, I have tried using XNA's BasicEffect, which rendered the model as expected with the materials I had set in maya. Now though, when I'm using my own HLSL effect file, there's always an error saying that my model doesn't have any colors The current vertex declaration does not include all the elements required by the current vertex shader. Color0 is missing. My HLSL effect file (partially leared from riemers.net) float4x4 xWorldViewProjection float4x4 xWorld float3 xLightPos float xLightPower float xAmbient struct VertexToPixel float4 Position POSITION float4 Color COLOR0 float3 Normal TEXCOORD0 float3 Position3D TEXCOORD1 struct PixelToFrame float4 Color COLOR0 float DotProduct(float3 lightPos, float3 pos3D, float3 normal) float3 lightDir normalize(pos3D lightPos) return dot( lightDir, normal) VertexToPixel SimplestVertexShader(VertexToPixel input) VertexToPixel Output (VertexToPixel)0 Output.Position mul(input.Position, xWorldViewProjection) Output.Normal normalize(mul(input.Normal, (float3x3)xWorld)) Output.Position3D mul(input.Position3D, xWorld) Output.Color input.Color return Output PixelToFrame OurFirstPixelShader(VertexToPixel PSIn) PixelToFrame Output (PixelToFrame)0 float diffuseLightingFactor DotProduct(xLightPos, PSIn.Position3D, PSIn.Normal) diffuseLightingFactor saturate(diffuseLightingFactor) diffuseLightingFactor xLightPower Output.Color PSIn.Color (diffuseLightingFactor xAmbient) return Output technique Simplest pass Pass0 VertexShader compile vs 3 0 SimplestVertexShader() PixelShader compile ps 3 0 OurFirstPixelShader() And my XNA code foreach (ModelMesh mesh in MainRoom.Meshes) foreach (ModelMeshPart meshPart in mesh.MeshParts) meshPart.Effect roomEffect.Clone() ... private void DrawModel(Model model, Matrix world) Matrix bones new Matrix model.Bones.Count model.CopyAbsoluteBoneTransformsTo(bones) foreach (ModelMesh mesh in model.Meshes) foreach (Effect currentEffect in mesh.Effects) Matrix worldMatrix bones mesh.ParentBone.Index world roomEffect.CurrentTechnique roomEffect.Techniques "Simplest" currentEffect.Parameters "xWorldViewProjection" .SetValue(worldMatrix camera.view camera.projection) currentEffect.Parameters "xWorld" .SetValue(worldMatrix) currentEffect.Parameters "xLightPos" .SetValue(lightPos) currentEffect.Parameters "xLightPower" .SetValue(lightPower) currentEffect.Parameters "xAmbient" .SetValue(ambientPower) mesh.Draw() I'm fairly new to HLSL (but not to XNA though), any help would be nice. EDIT I have also tried rendering a different model with materials, but it just gives the same error. Solution Thanks to Cole Campbell's answer and, the full working code can be found here |
12 | Ball bouncing infinitely and constantly Alright, so I've got hold of some simple physics mechanics, and am currently trying to implement bouncing. Based on the first answer of this question, I've developed the following algorithm Vector2 velocity float gravity float elasticity Hitbox dummy void bounce() dummy.MoveY(velocity.Y) velocity.Y gravity if (dummy.ThereWasContact.South) velocity.Y elasticity Gravity can be any value, and Elasticity is always between 0.0f and 1.0f. Velocity.Y's initial value can also be anything. Weight factors aside, which would determine a minimal rebound force for the object to be able to leave the ground again and (probably) aren't related to the problem, this is apparently fallacious. What happens here is somewhat like this If I drop an object from a height of 128 units, for example, 0u marking ground height, with a gravity of 1u and elasticity of 0.9, the object would bounce once, reach a maximum height of 126u from the rebound, and from then on keep alternating on maximum heights between this and 122u. This example is based on one of my own experiments, in which I drop an object from a height of 64 pixels and there is a floor at 192 pixels. The maximum height will keep going from 66 pixels to 70. What am I missing? Does weight after all do more than I think? If I need to explain something better or details appear to be missing, let me know. |
12 | 3d bounding Box border xna So, I'm trying to develop a 3d table tennis game, and I'm having problems when it comes to colliding the ball with the table. I have a bounding sphere for the ball and bounding box for the table, but the intersection isn't that accurate, and I'm guessing that the bounding box is incorrect since colliding the ball with the racket is good. I'm trying to display the bounding box so that it would be easier to see where the error is, but I cant seem to implement the tutorials I've found with my code, or just don't know how. And, I'm I right in creating an AABB since my table isn't moving? If anyone could help, it would be greatly appreciated, or if anyone could suggest a better way to collide a ball with a box (if there is) thanks. I've pasted my bounding box detection, and the collision between the sphere and box. If more code is needed I'll post it. Thanks http pastebin.com NDYmhXCh http pastebin.com 47vwJWSc |
12 | XNA blurring moving images Why does XNA blurs the images which moves less than 1px in between two draws? It is quite annoying, because everything looks really blurry. Is there a way to disable it? I have tried to set the SamplerState of the spritebatch's SamplerState to PointWrap in it's Begin function, but then it wraps the images to pixels, thus they move choppy. Any suggestions? Thanks! My SpriteBatch's Begin function spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend) Edit public class Image IDisplay public Texture2D texture private BaseModel model private Vector2 position private Util.DISPLAY LAYERS layer public Image(String asset, BaseModel model) model model texture Main.current.Content.Load lt Texture2D gt (asset) DisplayManager.add(this, model.layer) This is how the Image class looks like (without additional functions), and this is it's draw function which is being called. public void Draw(SpriteBatch batch) if (model null) batch.Draw(texture, position, Color.White) else position.X (int)Math.Round(model.Position.X, MidpointRounding.AwayFromZero) position.Y (int)Math.Round(model.Position.Y, MidpointRounding.AwayFromZero) batch.Draw(texture, position, Color.White) |
12 | 2D XNA C Texture2D Wrapping Issue Working in C XNA for a Windows game I'm using Texture2D to draw sprites. All of my sprites are 16 x 32. The sprites move around the screen as you would expect, by changing the top X Y position of them when they're being drawn by the spritebatch. Most of the time when I run the game, the sprites appear like this and when moved, they move as I expect, as one element. Infrequently they appear like this and when moved it's like there are two sprites with a gap in between them it's hard to describe. It only seems to happen sometimes is there something I'm missing? I'd really like to know why this is happening. Edit Adding Draw code as requested This is the main draw routine it first draws the sprite to a RenderTarget then blows it up by a scale of 4 protected override void Draw(GameTime gameTime) Draw to render target GraphicsDevice.SetRenderTarget(renderTarget) GraphicsDevice.Clear(Color.CornflowerBlue) Texture2D imSprite null spriteBatch.Begin(SpriteSortMode.FrontToBack, null, SamplerState.PointWrap, null, null) ManSprite.Draw(spriteBatch) base.Draw(gameTime) spriteBatch.End() Draw render target to screen GraphicsDevice.SetRenderTarget(null) imageFrame (Texture2D)renderTarget GraphicsDevice.Clear(ClearOptions.Target ClearOptions.DepthBuffer, Color.DarkSlateBlue, 1.0f, 0) spriteBatch.Begin(SpriteSortMode.FrontToBack, null, SamplerState.PointClamp, null, null) spriteBatch.Draw(imageFrame, new Vector2(0, 0), null, Color.White, 0, new Vector2(0, 0), IM SCALE, SpriteEffects.None, 0) spriteBatch.End() This is the draw routine for the Sprite class public virtual void Draw(SpriteBatch spriteBatch) spriteBatch.Draw(Texture, new Vector2(PositionX, PositionY), null, Color.White, 0.0f, Vector2.Zero, Scale, SpriteEffects.None, 0.3f) |
12 | 'perfect' platformer base Xna When a player touches a ground peice in a game, he seems to sink through the ground then slowly rise back up, and when he has risen back up, he is very jittery. if (touchingTheGround()) player.velocity.Y 2 touchground false the collision method sets the variable touchground to true if the player touches a ground peice, and if i dont set it to false, the collision detection wont work at all. i set the players velocity to move 2 up because when he's not touching a platform, his velocity.Y 1. How do i achieve a way so that the player Does not sink in the ground before moving up Stops jittering when its position is higher than the ground its touching |
12 | How can I use a Texture2D larger than 2048 x 2048? I'm having issues working with a large image. I've read other threads on using images larger than a Texture2D supports, but found nothing that addresses my problem specifically with implementation hints. My screen resolution is 1920 x 1080. I'm working in C XNA. The game in question is pretty much a board game. I have an 3840 x 3840 image I planned to use for the terrain map. The idea was to make each new game look a little different from the last by having the program randomly select a 1920 x 1080 segment of that large image to display. My code to randomly select and display a part of the image is working. Unfortunately, I can't even get the initial 3840 x 3840 image to load. Just picking "Add Existing Item" and adding the image to the content window on the right causes my program to error that a Texture2D can only be 2048 x 2048 maximum. How do I best handle this? I may later need to scale or rotate the map. Suggestions I've seen around Cut it up into sections. Use a smaller image that is made "seamless" or "tile able", then choose a random starting X,Y point in it and fill the screen with that. Are these good ways to go about it? How would I actually do this? Would I still be able to scale and rotate the map? |
12 | Alpha From PNGs Butchered I have a pretty vanilla Monogame game. I'm using PNG for all my sprites (made in Photoshop). I noticed that XNA is butchering the aliasing no matter what I do, my graphics appear jaggedy. Below is a screenshot. The bottom half is what XNA shows me when I zoom in 2X using a Matrix on my GraphicsDevice (to make the effect more obvious). The top is when I pasted the same sprites from Photoshop and scaled them to 200 . Note that partially transparent pixels are turning whiteish. Is there a way to fix this? What am I doing wrong? Here's the relevant call to draw to the SpriteBatch spriteBatch.Draw(this.texture, this.positionVector, null, Color.White, this.Angle, this.originVector, 1f, SpriteEffects.None, 0f) (this.positionVector can easily be Vector.Zero Color.White as 100 alpha, I think this.Angle can be a real angle (small gt in the image) or zero (the orb itself). |
12 | XNA Required information to represent 2D Sprite graphically I was thinking about dividing my game engine into 2 threads render thread and update thread (I can't come up on how to divide update thread from physic thread at the moment). That said, I have to duplicate all Sprite informations, what do I really need to represents a 2D Sprite graphically? Here are my ideas (I'll mark with ? things that I'm not sure) Vector2 Position float Rotation ? Vector2 Pivot ? Rectangle TextureRectangle Texture2D Texture Vector2 ImageOrigin ? (is it tracked somewhere else?) If you have any suggestion about using different types for datas, it's appreciated Last part of the question isn't this a lot of data to copy in a buffer?what should I really copy in the buffer?I'm following this tutorial http www.sgtconker.com 2009 11 article multi threading your xna 3 Thanks UPDATE 1 Newer values at the moment Vector2 Position float Rotation Vector2 Pivot Rectangle TextureRectangle Texture2D Texture Color Color byte Facing (can be left or right, I'll do it with an enum) I re read the tutorial, what I was doing wrong is not that I need to pass all those values, I need to pass only changed values as messages. UPDATE 2 Vector2 Position float Rotation Vector2 Pivot Rectangle TextureRectangle Texture2D Texture Color Color bool Flip uint DrawOrder Vector2 Scale bool Visible ? Mhhh, should Visibile be included? |
12 | Is it possible to animate the texture of a model? Below is how far I've got. I just made a simple block with user primitives to test it. But I haven't found a way to crop the spritesheet. textureLava frames activeFrame This line is how I want it but off course this doesn't work. Is there a way to crop this spritesheet or is there another way to animate the texture of a model? public void CreateFrames() for (int i 0 i lt 64 i ) frames.Add(new Rectangle(WIDTH i, i, WIDTH, HEIGHT)) public override void Update(GameTime gameTime) if (System.Environment.TickCount lastFrameTime gt TIME BETWEEN FRAMES) activeFrame lastFrameTime System.Environment.TickCount if (activeFrame gt 15) activeFrame 0 textureLava frames activeFrame gt DOESN'T WORK base.Update(gameTime) public override void Draw(GameTime gameTime) effect.TextureEnabled true effect.World Matrix.Identity effect.View Camera.ActiveCamera.View effect.Projection Camera.ActiveCamera.Projection effect.Texture textureLava foreach (EffectPass pass in effect.CurrentTechnique.Passes) pass.Apply() GraphicsDevice.SetVertexBuffer(vertexBuffer) GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, 10) |
12 | XNA Load Unload logic (contentmanager?) I am trying to make a point and click adventure game with XNA, starting off simple. My experience with XNA is about a month old now, know how the classes and inheritance works (basic stuff). I have a problem where I cannot understand how I should load and unload the textures and game objects in the game, when the player transitions to another level. I've googled this 10 times, but all I find is hard coding while I don't even understand the basics of unloading yet. All I want, is transitioning to another level (replacing all the sprites with new ones). Thanks in advance |
12 | Absorbtion 2d image effect I want to create a specyfic 2d image effect. It consists in modifying a sprite so it looks like it is being zoomed to a point or "absorbed" by that point. I'm not really sure what is the technical name of this effect so I cannot explain it correctly. Here you can see a video of what I'm talking about, it is the effect when the character absorbs the three glyphs. http www.youtube.com watch?v PIo GddsMcU amp t 4m45s What is the name of this effect? How can I implement it with XNA for 2D textures sprites? |
12 | Getting wrong value for middle of screen My mouse is able to move the camera and rotate it around my model. If the mouse is in the middle of the screen, the camera should not move. The red circle is where my mouse has to be at in order for the camera to stay still. If I put the cursor in the middle of the screen, it rotates the camera which shouldn't happen. Point screenCenter float scrollRate 1.0f MouseState previousMouse bool moveMode false region MOUSE screenCenter.X this.Window.ClientBounds.Width 2 screenCenter.Y this.Window.ClientBounds.Height 2 this.IsMouseVisible true previousMouse Mouse.GetState() Mouse.SetPosition(screenCenter.X, screenCenter.Y) endregion MOUSE if (this.IsActive) MouseState mouse Mouse.GetState() if (moveMode) Vector3 temp player.playerWorld.Translation player.playerWorld.Translation Vector3.Zero player.playerWorld Matrix.CreateRotationY(MathHelper.ToRadians(mouse.X screenCenter.X) 75) player.playerWorld.Translation temp cam.up MathHelper.ToRadians(mouse.Y screenCenter.Y) 25 if (mouse.RightButton ButtonState.Pressed) if (graphics.GraphicsDevice.Viewport.Bounds.Contains(new Point(mouse.X, mouse.Y))) moveMode true else if (moveMode) moveMode false if (mouse.ScrollWheelValue previousMouse.ScrollWheelValue ! 0) float wheelChange mouse.ScrollWheelValue previousMouse.ScrollWheelValue cam.up 0.7f cam.backward 0.7f previousMouse mouse Why could this be happening? the screen is 650X1000. ScreenCenter x and y are the correct values. Now that I play with it more, it seems each time the game starts, the mouse is set to a different position. The mouse should automatically be set to the middle of the screen each time the game starts, but it ends up anywhere but the middle. Any idea of what could be happening here? |
12 | Custom VertexDeclaration for Color, Texture, Normal What is the best way to create a VertexDeclaration, that makes it able to render a Shape consisting of vertices and also be able to store a color for the shape (in case the texture can't be rendered or in case we want color instead of a texture) instead of having both a VertexPositionNormalTexture and a VertexPositionColor struct in the same class struct. I'm trying this approach public interface IShape IVertexType public struct ShapeFace public int Count get set public Color Color get set public Vector3 Position get set public Vector2 TextureCoordinates get set public Vector3 Normal get set public Vector3 Vertices get set Perhaps I need this? public int Indexs get set public struct Shape IShape public ShapeFace Faces get set Need to implement VertexDeclaration here How do I implement the VertexDeclaration to understand what I want to do? A shape contains faces, each face can have it's own texture OR color, normal mapping, texture coordinates, etc. Example A cube has 6 faces, each face needs 2 triangles, each triangle has 3 points. 6 2 3 36 vertices. This way I can create a cube with 6 faces instead of 36 vertices, and render it in color or with a texture. I really want to simplify it so that I can create some kind of struct that works this way. |
12 | Why is XmlSerializer adding junk to the end of my file? I'm making a game and I am serializing the save game data. The data is simply a few lists of bools, ints and floats. But about 50 of the time I get an error when the data tries to save or load that says "There is an error in XML document." The error is always located at the end of the file, even after it has changed size or I have added other variables. It appears that very last part of the XML data is getting copied twice. The last line of the XML should read lt LevelStats gt But when an error occurs it often reads lt LevelStats gt gt Or lt LevelStats gt tats gt Or some other small part of the last line duplicated. Here is the class I am serializing using System using System.Collections.Generic using System.Linq using System.Text using System.Xml.Serialization using Microsoft.Xna.Framework.Storage using System.IO namespace Jetpack.Classes Serializable public struct LevelStats Player Bests public List lt float? gt fTimeList public List lt int? gt iScoreList public List lt int? gt iFuelList Time public List lt bool gt bBronzeTimeList public List lt bool gt bSilverTimeList public List lt bool gt bGoldTimeList Score public List lt bool gt bBronzeScoreList public List lt bool gt bSilverScoreList public List lt bool gt bGoldScoreList Fuel public List lt bool gt bBronzeFuelList public List lt bool gt bSilverFuelList public List lt bool gt bGoldFuelList Level Complete public List lt bool gt bIsLevelComplete And here are my methods for saving the loading the data region Save amp Load Level Stats public static void SaveLevelStats(LevelStats levelStats, string filename) Get the path of the save game string fullpath System.IO.Path.Combine(Directory.GetCurrentDirectory(), filename) Open the file, creating it if necessary FileStream stream File.Open(fullpath, FileMode.OpenOrCreate) try Convert the object to XML data and put it in the stream XmlSerializer serializer new XmlSerializer(typeof(LevelStats)) serializer.Serialize(stream, levelStats) finally Close the file stream.Close() public static LevelStats LoadLevelStats(string filename) LevelStats levelStats Get the path of the save game string fullpath System.IO.Path.Combine((Directory.GetCurrentDirectory()), filename) Open the file FileStream stream File.Open(fullpath, FileMode.OpenOrCreate, FileAccess.Read) try Read the data from the file XmlSerializer serializer new XmlSerializer(typeof(LevelStats)) levelStats (LevelStats)serializer.Deserialize(stream) finally Close the file stream.Close() return (levelStats) endregion Why am I getting the error above? |
12 | Exporting XNA class library as a DLL file I have downloaded an open source project that I intend to use with my current game. The download came with all the class files from the original project as well as a pre compiled DLL file representing the project. I was able to easily link this DLL with my current project and get it working just fine, no problems there. The problem I now have is that I want to make a couple of changes to the original libraries (extend its functionality a bit to better suit my needs) and re export the class library as a DLL again, but I have no clue how to do this. Is there some simple way in VS where I can just take the class library and export compile it as a DLL file again or is there more to it than that? This seems like something that should be pretty simple but my efforts to find an answer have so far come up with nothing. Thanks in advance. |
12 | Orbiting a camera around the Y axis whilst remaining up I've been having difficulty with a problem which I thought was going to be a simple solution. I have a camera facing downwards on a character. The can camera be lowered and when it's lowered it remains the same distance away from the character that it was (basically rotating around the X axis of the target). Now what I want it to be able to do is spin around the character on the Y axis as well, but to maintain the same distance and to remain upwards all the time. The problem I'm having is that if I do something similar to the way I did it on the X axis everything becomes a mess. First of all it doesn't remain facing up, as it spins the camera ends up upside down and i'm not really sure how to recalculate the up vector for it. But ontop of that it doesn't maintain the same distance from the character at all times. This is what I have right now cameraUp new Vector3(0, 1, 0) cameraPosition new Vector3(cameraOffset.X, cameraOffset.Y, cameraOffset.Z) cameraPosition Vector3.Transform(cameraPosition cameraTarget, Matrix.CreateFromAxisAngle(Vector3.UnitX, tippingAngle)) cameraTarget This is the part that I'm having difficulty with, the rest works fine. cameraPosition Vector3.Transform(cameraPosition, Matrix.CreateFromAxisAngle(Vector3.UnitY, rotationAngle)) view Matrix.CreateLookAt(cameraPosition, cameraTarget, cameraUp) EDIT Thank you to everyone, all of your comments helped. The biggest issue was that somehow I let it slip past that the cameraUp value was wrong, I think it happened as a typo when I was tidying the code up. Anyway, after fixing that the code above was exactly what I needed. I had tried that before but because the up vector was wrong I was getting really weird results so thanks to everyone. ) |
12 | Making entire scene fade to grayscale When the player loses all of their lives, I want the entire game screen to go grayscale, but not stop updating immediately. I'd also prefer it fade to grayscale instead of suddenly lose all color. Everything I've found so far is either about taking a screenshot and making it grayscale, or making a specific texture grayscale. Is there a way to change the entire playing field and all objects within to grayscale without iterating through everything? |
12 | Weird white outline around model I'm working on a game in XNA 4 and I recently switched to a deferred shading implementation following this guide. A strange white outline is showing up on my models now and I'm not sure whats causing this. I thought maybe it was a lack of precision on the normal render target or the depth render target but increasing them to 64 bits (Rgba64) instead of 32 (Color) didn't help. I also thought it might be some problem with the specular calculation so I tried setting the specular to 0 but that didn't help either. Debugging the pixel in PIX shows the diffuse value is being calculated as nearly white for that pixel. Any ideas? I included a picture of the problem below, it's easier to see it at full size. Pixel Shader float4 PixelShaderFunction(VertexShaderOutput input) COLOR0 input.ScreenPosition.xy input.ScreenPosition.w float2 texCoord 0.5f (float2(input.ScreenPosition.x, input.ScreenPosition.y) 1) halfPixel float4 normalData tex2D(normalSampler, texCoord) Transform normal back into 1, 1 range float3 normal normalize(2.0f normalData.xyz 1.0f) float specularPower normalData.a float specularHardness tex2D(colorSampler, texCoord).a 255 float depthVal tex2D(depthSampler, texCoord).r Compute screen space position float4 position float4(input.ScreenPosition.xy, depthVal, 1.0f) Transform to world space position mul(position, InvertViewProjection) position position.w Surface to light vector float3 lightVector lightPosition position float3 projectedTexCoords position lightPosition projectedTexCoords mul(projectedTexCoords, float3x3( float3( 1, 0, 0), float3(0, 1, 0), float3(0, 0, 1))) float distanceToLight length(lightVector) lightRadius float shadow ShadowContribution(projectedTexCoords, distanceToLight) float attenuation saturate(1.0f distanceToLight) lightVector normalize(lightVector) Compute diffuse light float normalDotLight max(0, dot(normal, lightVector)) float3 diffuseLight normalDotLight Color.rgb float3 reflectionVector normalize(reflect( lightVector, normal)) float3 directionToCamera normalize(cameraPosition position) float specularLight specularPower pow(saturate(dot(reflectionVector, directionToCamera)), specularHardness) return shadow attenuation lightIntensity float4(diffuseLight.rgb, specularLight) Edit Sorry about the JPG, stackexchange's uploader did that on its own. Roy T I did actually reference your XNA4 conversion of the tutorial for the parts that changed from XNA3. Since I didn't make any big changes to the code I thought maybe this bug existed in the original but was just impossible to see with so many lights all moving around, so I removed all but one light and the bug showed up again (look near the lizard's elbow) Here are the GBuffer contents for my scene Color Buffer Depth Buffer Normal Buffer Final Render Edit2 I'm starting to suspect the problem is CombineFinal.fx when it samples the color map. This is the computation for a properly colored pixel right next to a white pixel diffuseColor (0.435, 0.447, 0.412) diffuseLight (1.000, 1.000, 0.902) light (1.000, 1.000, 0.902, 0.000) PixelShaderFunction (0.435, 0.447, 0.371, 1.000) specularLight 0.000 And this is the output from an improperly colored white pixel directly next to it diffuseColor (0.824, 0.792, 0.741) diffuseLight (1.000, 1.000, 0.902) light (1.000, 1.000, 0.902, 0.000) PixelShaderFunction (0.824, 0.792, 0.669, 1.000) specularLight 0.000 The diffuseColor is the only difference, and this color is taken directly from the color map. Perhaps there is a slight error in the computation of the texture coordinate to sample from? Lighting Pass |
12 | Hex tile systems and the efficient use of classes So I've built myself a system of classes for what I think is an efficient way to describe an entity that would live in my game. Is this an effective approach or am I creating entities that are too large in size? I want the game to be able to run well even with an inane amount of tiles. I read the post (Map with 20 million tiles makes game run out of memory, how do I avoid it?) about having one million tiles and memory problems and I'm worried that my tile system I've created using the entity system will not be able to handle such large sized maps as there is so much information to be processed. To give you an idea about what each component of a Hex Entity holds, the sprite comp maintains the following variables the texture, position, rotation, height and width while the hex comp of the hex entity maintains the position, the coordinates on the board, the orientation, and what hex's are adjacent to it. Should i simplify the date types |
12 | How to adjust GUI to screen resolution ? I've created a GUI for my XNA game and now I'm stuck with a problem. My GUI element positions are designed for a max resolution of 1920x1080, and if I try changing it to 640x480 they disappear from the screen. What I can change to keep them there? |
12 | How do I find two points at an angle on opposite sides of a circle? With reference to my previous question I'm using micklh's answer, which works perfectly. However, it calculates the gradient based on two points, a starting point and an ending point. I want to change that such that I can give it a center point, an angle in degrees, and a length. If you look at the picture from the other question You can sort of discern where the center point is, the x,y of starting ending locations become the dots based on the length of the gradient. I assume I would have to Take the center location Apply the angle length Gives me my ending x,y Take the center location Calculate the reverse angle Apply the reverse angle length Gives me my starting x,y Plug these starting ending positions to the answer from the other question. Am I correct? How would I do those steps? |
12 | How much to modify yaw? XNA 4.0 Heres a picture that explains better than my words can For rotating an object I'm using quaternions. CreateFromAxisAngle(vector3.Right,yaw) Maybe this isn't how I should be doing it but I also keep my yaw as radians that are always between 0 and 360 more or less than 0 or 360 puts it at 0 or 360 respectively. (object is build up of vertices and indices) I can rotate it no problem. Move it all about. But what I really want to do is to find how much I should alter the yaw so that the my models right vector will sync up with the line I can draw between the objects center and the camera's position(y is always 0). Which I guess is the problem now, but long term I am trying to find how I modify the yaw to match any direction. Say I am travelling Left, I may want to rotate my yaw so that my objects forward is also left. I have been researching here and elsewhere and there seem to be solutions, I just can't wrap my head around any. Maybe someone could help shed some light? |
12 | Is there any way to enable the HiDef graphics profile property on a Silverlight 5 3d Web App? I have an XNA Windows Game that uses the HiDef profile to load complex fbx and obj files. Trying to move it over to a Silverlight 3d Web App, Silverlight seems to only want to use the Reach profile, and I get an error that the Reach profile does not support a sufficient number of primitive draws per call. Is there any way to change to HiDef in Silverlight 5? It is not in the project properties and attempting to change it in mainpage.xaml.cs only gives me the option of setting it to Reach. |
12 | Ball bouncing infinitely and constantly Alright, so I've got hold of some simple physics mechanics, and am currently trying to implement bouncing. Based on the first answer of this question, I've developed the following algorithm Vector2 velocity float gravity float elasticity Hitbox dummy void bounce() dummy.MoveY(velocity.Y) velocity.Y gravity if (dummy.ThereWasContact.South) velocity.Y elasticity Gravity can be any value, and Elasticity is always between 0.0f and 1.0f. Velocity.Y's initial value can also be anything. Weight factors aside, which would determine a minimal rebound force for the object to be able to leave the ground again and (probably) aren't related to the problem, this is apparently fallacious. What happens here is somewhat like this If I drop an object from a height of 128 units, for example, 0u marking ground height, with a gravity of 1u and elasticity of 0.9, the object would bounce once, reach a maximum height of 126u from the rebound, and from then on keep alternating on maximum heights between this and 122u. This example is based on one of my own experiments, in which I drop an object from a height of 64 pixels and there is a floor at 192 pixels. The maximum height will keep going from 66 pixels to 70. What am I missing? Does weight after all do more than I think? If I need to explain something better or details appear to be missing, let me know. |
12 | Efficient Tile based collision detection for a lot of squares? currently I am working on my own take of a tile based game (think Terraria, but less fantastical (I think that's a word? Sorry if it isn't)). Anyway, I currently have collision detection working (for corner cases even!) which was a big step for me. There is something extremely gratifying about seeing a sprite not run through a block. But then I had the idea to benchmark. Bad idea. 1,000 squares, no problem. 10,000 squares, for 3 characters was kind of laggy. 100,000 squares (really huge map), for 3 characters was unplayable. I'm having the issue where I don't want to even consider the blocks that are too far from the player, characters, items, etc., but I don't want to load those in out of memory constantly. Here's my algorithm so far, feel free to criticize. foreach (Block in level) if (distance from block to player gt a specified amount) ignore this block else get the intersection depth between the two bounding boxes if (depth of intersection ! Zero vector) check y size vs x size resolve on smallest axis As you will note, when the level size get's bigger, the Order of this algorithm grows by N blocks. I would like to not even consider blocks that aren't even near the player. I'm thinking maybe use a (0,0) to (mapWidth,mapHeight) double array of blocks instead of a list, calculating a danger zone depending on the person's position e.g., if player's position is at (10, 20) it will look from (0, 10) to (20, 30), or so on. Any thoughts and considerations are awesome, thank you. |
12 | How to update "dynamicVertexBuffer" correctly with "setdata" on XNA? I developed a small 3d games xna and uses a "DynamicVertexBuffer" and "DynamicIndexBuffer" to store and draw my vertices. Everything works fine, but my problem is the "Update" function where I update my buffer. Each apel update I have to reset my buffer using the keyword "new DynamicVertexBuffer (...." It goes down the performance and reduce the frames per second of my games. Do I have to initialize my buffer each time in my function "Update ()"? Is it okay to reset every time my buffer to each call frame I can not find a solution to update correctly my Dynamicbuffer with "setData ()" function without having to initialize whenever my buffer just before. Am I obliged to Reset "DynamicVertexBuffer" and "DynamicIndexBuffer" before the update? If I call "setData ()" before reset it, I throw an exception Works well but I have initialized every time "dynamicIndexBuffer" and "dynamicVertexBuffer" before update! (Consumes more resources?) public override void Update(GameTime gameTime) foreach (Octree.Node node in regions regionIndex .Nodes.Where(n gt n.ItemGroup a).Where(m gt arcadia.camera.Frustum.Contains(m.boundingBox) ! ContainmentType.Disjoint)) build indices node.Cube.SetUpIndices(indexIndiceBuild) Add indices tho the collectionList foreach (int indice in node.Cube.Indices) list structure indices.Add(indice) Add vertex to the collectionList foreach (VertexPositionTexture posText in node.Cube.Vertices) vertexPositionStructureCube.Add(posText) Add vertexBuffer to the collectionList indexIndiceBuild 24 Declare and initialize new buffers VertexBuffer Initialize again vertexBuffer cube new DynamicVertexBuffer( arcadia.Game.GraphicsDevice, VertexPositionTexture.VertexDeclaration, vertexPositionStructureCube.Count, BufferUsage.WriteOnly) VertexBuffer SetData (update) vertexBuffer cube.SetData lt VertexPositionTexture gt (vertexPositionStructureCube.ToArray()) IndexBuffer Initialize again indexBuffer cube new DynamicIndexBuffer(Game.GraphicsDevice, IndexElementSize.ThirtyTwoBits, list structure indices.Count, BufferUsage.WriteOnly) IndexBuffer SetData (update) indexBuffer cube.SetData(list structure indices.ToArray()) ......... I'm just trying to update with "SetData" with new vertices and indices but i throws the exception "The array is not the proper size for the Amount of data requested." public override void Update(GameTime gameTime) ......... Only "setdata()" without initialize buffer again ?? VertexBuffer SetData (update) vertexBuffer cube.SetData lt VertexPositionTexture gt (vertexPositionStructureCube.ToArray()) IndexBuffer SetData (update) indexBuffer cube.SetData(list structure indices.ToArray()) ......... |
12 | How to attach two XNA models together? I go back on unsolved question I asked about attaching two models together, could you give me some help on this ? For example, If I want to attach together Model1 ( Main model) amp Model2 ? I have to get the transformation matrix of Model1 and after get the Bone index on Model1 where I want to attach Model2 and then apply some transformation to attach Model2 to Model1 I wrote some code below about this, but It does not work at all !! (6th line of my code seems to be wrong !?) Model1TransfoMatrix New Matrix Model1.Bones.Count Index Model1.bone x .Index foreach (ModelMesh mesh in Model2.Meshes) foreach(BasicEffect effect in mesh.effects) matrix model2Transform Matrix.CreateScale(0.1.0f) Matrix.CreateFromYawPitchRoll(x,y,z) effect.World model2Transform Model1TransfoMatrix Index effect.view camera.View effect.Projection camera.Projection mesh.draw() |
12 | Is there a good way to get pixel perfect collision detection in XNA? Is there a well known way (or perhaps reusable bit of code) for pixel perfect collision detection in XNA? I assume this would also use polygons (boxes triangles circles) for a first pass, quick test for collisions, and if that test indicated a collision, it would then search for a per pixel collision. This can be complicated, because we have to account for scale, rotation, and transparency. WARNING If you're using the sample code from the link from the answer below, be aware that the scaling of the matrix is commented out for good reason. You don't need to uncomment it out to get scaling to work. |
12 | Reusing a render target to create multiple Texture2D's (XNA) i want to be able to loop through a hole bunch of textures, and render them on an object. I then want the rendered image to be placed onto a texture2D. The point? well hopefully i will end up with an array of Texture2D's containing a model with multiple skins. Here's my code for (byte i 1 i lt allBlockIso.Count() i ) DisplayBox.SetValue(i) GraphicsDevice.SetRenderTarget(cubeTarget) GraphicsDevice.Clear(Color.Transparent) DrawIsoCube() GraphicsDevice.SetRenderTarget(null) allBlockIso i (Texture2D)cubeTarget DisplayBox.SetValue is a function which goes through and sets the texture. This is working! DrawIsoCube() draws the cube (the test model) and this is working too. The problem is definitely something to do with the unreusability of the render target. Pretty simple yet it's not working. It appears that whatever the last image being rendered is, is shown in every image of the allBlockIso array. Anyone know a fix? Cheers. P.S. sorry if this wan't explained well. I'm not very good at explaining P |
12 | Monogame XNA Is there a limit when drawing at far position ( 1 billion ? strange behavior) So I'm making an "unlimited" 2D Tile Engine with procedural generation (simple noise based) in Monogame, and I'm loading unloading Chunck by Chunck as you go along. It's working pretty well now. Only problem I encounter when I'm positioning my character at a high value like for example int.Maxvalue 2 (and higher), drawing tiles and every sprites from a high Position becomes all glitchy. Tiles take random sizes with a higher width and height (see pictures). Drawing tiles spriteBatch.Draw( textToDraw, new Vector2(i TILE SIZE, j TILE SIZE), new Rectangle(0, 0, TILE SIZE, TILE SIZE), drawColor, 0, new Vector2(0, 0), 1f, SpriteEffects.None, depth ) Camera Transform public Matrix Transform(GraphicsDevice graphicsDevice) m Transform Matrix.CreateTranslation(new Vector3( m CameraPosition.X, m CameraPosition.Y, 0.0f)) Matrix.CreateTranslation(new Vector3(graphicsDevice.Viewport.Width 0.5f , graphicsDevice.Viewport.Height 0.5f , 0.0f)) on redivise par 0.5 cause du renderTarget 720x450 return m Transform Begin spriteBatch matrix this.Manager.camera.Transform(this.GraphicsDevice) spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, SamplerState.PointClamp, null, null, null, matrix ) Drawing at position x 1 million, y 1 million Drawing at position x 1 billion, y 1 billion Red tile is a random tile I draw in another color to be able to get the size. But all the tiles are glitchy. To isolate the problem as it didn't seem to come from my code, I tested in an Internet XNA sample I modified (From xnagpa.net "Eyes of the Dragons" samples) working with a similar Camera and tile engine. I forced the Camera position to a high value (x 1 billion, y, 1 billion) and drawing Tiles on the screen at that position. Same problem. So my newb guess is it has to do with calculation of the Matrix, but after that it gets too complicated for me. Anyone had the problem ? Can confirm it is a limitation of some sort. I don't think it can be fixed, but I'm trying to determine what is the "limit" of my "unlimited world". Code is from my code base, pictures are from the example I cited and modified |
12 | MonoGame SharpDX Error 'The Parameter is Incorrect' when using graphics.DrawUserPrimitives Below is a small section of code that is meant to draw a multicolored triangle to the middle of the screen in a MonoGame game. This uses the basic function DrawUserPrimitives to draw the triangle. This works fine in XNA, but the moment i try to use it in a MonoGame DX game (Which compiles using SharpDX) it will crash with the following error An unhandled exception of type 'SharpDX.SharpDXException' occurred in SharpDX.dll Additional information HRESULT 0x80070057 , Module General , ApiCode E INVALIDARG Invalid Arguments , Message The parameter is incorrect. Below is the code that is causing the error. private void SetUpVertices() vertices new VertexPositionColor 3 vertices 0 .Position new Vector3( 0.5f, 0.5f, 0f) vertices 0 .Color Color.Red vertices 1 .Position new Vector3(0, 0.5f, 0f) vertices 1 .Color Color.Green vertices 2 .Position new Vector3(0.5f, 0.5f, 0f) vertices 2 .Color Color.Yellow public void Draw(GameTime gameTime) gDevice.DrawUserPrimitives(PrimitiveType.TriangleList, vertices, 0, 1, VertexPositionColor.VertexDeclaration) Has anyone ever come across simillar errors using the DirectX version on MonoGame and SharpDX when dealing with primatives? And do you know of a way I can fix this issue? |
12 | 2D Grid based game how should I draw grid lines? I'm playing around with a 2D grid based game idea, and I am using sprites for the grid cells. Let's say there is a 10 x 10 grid and each cell is 48x48, which will have sprites drawn there. That is fine. But in design mode, I'd like to have a grid overlay the screen. I can do this either with sprites (2x600 pixel image etc) or with primitives, but which is best? Should I really be switching between sprites and 3d 2d rendering? Like so Thanks! |
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 | Controls become inverted after a collision I'm just prototyping a simple project. I'm moving a sprite on screen using the Xbox gamepad public override void Update(GameTime gameTime) gamePad GamePad.GetState(PlayerIndex.One) GetPlayerRotation() base.Velocity new Vector2(vSpeed.X gamePad.ThumbSticks.Left.X, vSpeed.Y gamePad.ThumbSticks.Left.Y) base.Update(gameTime) private void GetPlayerRotation() leftThumb gamePad.ThumbSticks.Left base.Rotation (float)Math.Atan2(leftThumb.Y, leftThumb.X) This works fine to move the sprite in the correct direction (Dependent on the angle of the joystick). However, the problem is, when I try to do a collision with a simple test object that is just a sprite, with a rectangle public virtual bool Collision(Entity entity1, Entity entity2) if (entity1.Rectangle.Intersects(entity2.Rectangle)) Debug.WriteLine("Collision") return true else return false foreach (TestBlock block in blockList) block.Update(gameTime) if(player.Collision(player, block)) player.vSpeed player.vSpeed Whilst this does work, and the speed is inverted, when the bool returns to false after the collision, the control scheme becomes inverted (I.e, pressing the thumbstick up moves the sprite down). I was trying to achieve a simple bounce effect off the block. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.