Jump to content

  • Log In with Google      Sign In   
  • Create Account


Member Since 19 Jul 2006
Offline Last Active Oct 04 2016 01:53 AM

#5248358 Scrolling background logic?

Posted by on 23 August 2015 - 08:51 AM

Another technique for horizontal and vertical background wrapping is to use UV linear wrapping state with the device so you only need to draw the background once and the hardware takes care of the wrapping.

First you need to figure out how to create a background that when wrapped - it won't appear to have seams. This can be done by copying the background to 4 layers with each layer moved to a corner with their tips touching in the center to expose the seams that would show when scrolling. Then with a 50% opaque stamp tool, smudge tricks and other art techniques to hide seams. Now this art can scroll without seams appearing.

  Then when rendering a texture, you would want the sampler state to use linear wrapping and when you draw it:

(using SamplerState.LinearWrap)

Draw(background, screenRect, new Rectangle((int)background_pos.X, (int)background_pos.Y, background.Width, background.Height), ColorTint); 


Where screenRect is your destination screen rectangle(always the same), and the other rectangle is the source rectangle (x,y, width, height). When the source sampling starts at x, y and exceeds the edges of the texture (cuz trying to go width and height), it will wrap the texture to continue sampling. So then when the player moves you just change background position in that direction.

For layers the same technique could be applied.

Hypothetically, for huge mapped backgrounds, you may want to seamlessly tile parts together and scroll through sections of the grid -- each tile in the grid can tell it which part of which background art to show. This way you could have extensive changes to background scenery as the foreground scrolls.

#5245886 The best way to manage sprite sheet animations?

Posted by on 11 August 2015 - 09:35 PM

I'm still kinda in that twisted nest of if-then boat myself. It works but it becomes quite complex with all the conditions that can exist.

The tricky thing is getting it to decide what portions of animations to select under a wide variety of conditions that will result in legal smooth motion with so many possible outcomes that don't make sense in some situations -- and still make the character reactions look quick, responsive, and animate fluidly.

For example - a tiny sample:

case HEROSTATE.blablabla:



if (((isJumping == false) && (slow_fall)) || (inWater && previous_jump_pressed == false)) //if not already jumping and didn't just press jump in previous loop:
    doubleJumping = false;
    if (jump_pressed) // more logic elsewhere
        int jump_type = 0; // 0 is normal, 1 is duck roll,...

        if (duck_initialized)
        { //if in duck mode:
            if ((!left_down) && (!right_down)) { animationPlayer.PlayAnimation(jumpUpAnimation); animationPlayer.frameIndex = 2; ducking = false; duck_initialized = false; customAnimator.animation = null; isGrounded = false; }
            if ((!rolling) || ((Math.Abs(velocity.X) < 2)))
                if (left_down)
                    if (facing == FACE_LEFT) { animationPlayer.PlayAnimation(rollForwardAnimation); velocity.X = max_speed.X * -2; }
                    if (facing == FACE_RIGHT) { animationPlayer.PlayAnimationBackward(rollForwardAnimation); velocity.X = max_speed.X * -2; }
                    rolling = true;
                    jump_type = 1;
                if (right_down)
                    if (facing == FACE_RIGHT) { animationPlayer.PlayAnimation(rollForwardAnimation); velocity.X = max_speed.X * 2; }
                    if (facing == FACE_LEFT) { animationPlayer.PlayAnimationBackward(rollForwardAnimation); velocity.X = max_speed.X * 2; }
                    rolling = true;
                    jump_type = 1;
            else jump_type = 1;
        if (jump_type == 0)
            velocity.Y = -jumpPower;
            isJumping = true;
            if ((inWater) && ((animationPlayer.animation == jumpForwardAnimation) || (animationPlayer.animation == jumpUpAnimation))) animationPlayer.frameIndex = 0;
else if (isJumping)


... etc..

So I map the possible behaviors and conditions on paper first and use that to figure out how to build conditions.

ie: flip-roll from ledge -- relying on falling state and playing fall animation would be faulty.

Based on suggestions I'm thinking maybe it's possible to set legal animation bridges between frames in other ways which again I'm thinking may still require conditional inputs such as velocity, water-interaction state, grounded-state, jump-state, crouch-state(ie: just starting, far enough into, just ending), knowledge of surrounding objects and Booleans set to qualify legality of certain transitions. Right now I actually have it choose frame transitions differently depending on what's happening as it enters another animation to satisfy what the player wants to do.

#5245782 The best way to manage sprite sheet animations?

Posted by on 11 August 2015 - 11:46 AM

Just adding..

I find the logic for animation switching can become quite complex depending on the sophistication of character interactions. I actually rewrote my animation class to be as simple as possible trying to minimize conditional switching as you mentioned.

Something like:


Character[Ryu].PlayAnimation(UpperCut, facing, [...optional parameters here...] );      // optionals would be like conditional play-speed(ie: underwater), etc..


(Depending on character - all my logic would be kept in a player or character class for determining animations)

Where PlayAnimation uses enumerated animation UpperCut, which is assigned the animation index. The Player plays a strip of animation from the sprite sheet based on predefined speed, position and so on which are also loaded from a file corresponding to the sheet. If you use a sheet packer, you may need to set up an editor to adjust the extraction boxes for each image you would normally use in an animation strip [otherwise you could even simply write the strip info into a text file or into header]. Also you could have it produce test play-back of the selected animation strip you're working on and provide additional information to save to file such as speed (or even frame timing for particular frames if you wanted).


It may be handy to also map out on paper - different conditions in which animations can or can't be triggered. ie: different animation triggered when ducking or jumping or running or idle. And then quickly switching animations to adapt to new user input. This is where it becomes very difficult to avoid complex if-then stuff.

#5241853 Are there any limitations to the DirectX Toolkit?

Posted by on 21 July 2015 - 09:06 PM

My personal experience with it - it has a lot of useful helpful functions that are highly efficient IMO and memory safe if used properly so I really like it. I use MonoGame/XNA but am also expanding a DX11 game engine at the same time, so I would say it has some things that are similar to XNA(which I likes), but you have the source code too so you can see how it works and understand how to make your own functions that do similar things. For example, I found the memory alignment helper(AlignedNew.h) very useful (inherit into your classes/structs) for 16 byte alignments (optimization). So since you can choose what you do or do not want to use and you can see the source code, I think it is useful in helping to learn DX11+ plus it does not bring any limitations and since it is very popularly used, I personally would assume it is here for the long run. You could even use it minimally if you wanted and just use the parts most useful to you.

#5234426 C# becoming obsolete ?

Posted by on 12 June 2015 - 05:13 AM

I thought c# was still gaining popularity. (plus I find it very easy to develop without bugs, workflow is quick, performance is good) -- also I came from a background of C/C++ and the transition to c# was extremely easy (feels like the same language) - so if you know one you can comprehend the other. I even noticed that I was able to follow a java tutorial and know how to make the same in c#  - a lot of similarity. A lot of game engines and frameworks are built around C# also.

  However it does seem java is gaining popularity too. I would want to brush up on C/C++/C# and Java (all similar) - for development ... and also php/css/javascript/sql would be useful in my limited opinion.


I remember in university some of our pompous pretentious professors told us C/C++ was already becoming obsolete(many years ago) and that we should only focus on learning Delphi(which I liked) and Eiffel - luckily I followed my instincts and bought a C++ compiler and focused there instead.

#5228901 2D Collision Mask DX9

Posted by on 13 May 2015 - 11:06 PM

I'm guessing a bool * mask :

bool * mask = new bool[width*height];


Maybe something like this?:


For each y, I'd get the start pixel of the row (cast to BYTE* - pitch is in bytes) like this:
D3DCOLOR* pixline = (D3DCOLOR*)((BYTE*)rect.pBits + rect.Pitch*y);


Then inside the x loop:
D3DCOLOR pixel = pixline[x];


Then set mask to true or false based on alpha bits:
mask[x+y*width] = ((pixel&0xFF000000)!=0x00);

#5224402 Animation Keyframes, Sampling, and Interpolation Questions

Posted by on 19 April 2015 - 08:05 PM

I would expect if the rotations weren't quite right, the heel would also deviate in the x axis a bit - but if none of the children receive any translations - it is weird that it would only move in the y direction -- unless somehow the rotation deviations were somehow perfectly altering to keep the heel on the x-axis -- in which case I'd be wondering about how it is baking the output data - maybe even wondering about animation-easing having some involvement. (?) 

#5204247 Save/Load in C# XNA

Posted by on 14 January 2015 - 11:46 AM

Some example code (based on what I do) - doing it this way makes it UAC compliant and I find it simple:

    public class PlayerData
        public int level;
        public Vector2 player_position;
        public int life;
        public int points;
    public class EnemyData
        public Vector2 enemy_pos;
        public Vector2 enemy_vel;
 public int enemy_life;
// IE:
    public EnemyData[] monsters;
    public PlayerData player;
    monsters = new EnemyData[MAX_MONSTERS];
    player = new PlayerData();

public bool SaveGame(int saveNumber) {
    string fileName = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); //CSIDL_LOCAL_APPDATA
    bool success = File.Exists(fileName);
    if (success) { }
    else {               
    bool success = true;
    FileStream fs = new FileStream(fileName, FileMode.Create);                   
    BinaryFormatter formatter = new BinaryFormatter();       
        if (player != null) formatter.Serialize(fs, player);
 if (monsters != null) formatter.Serialize(fs, monsters);
 // etc....
    catch (SerializationException e)        
        success = false;
        Console.WriteLine("Failed to serialize. Reason: " + e.Message);           
    finally { fs.Close();}

public bool LoadGame(string fileName)
    bool success = true;
    if (File.Exists(fileName) == false) { Console.WriteLine("File does not exist: " + fileName); return false; }
    FileStream fs = new FileStream(fileName, FileMode.Open);
        BinaryFormatter formatter = new BinaryFormatter();               
        player = (PlayerData)formatter.Deserialize(fs);
        monsters = (EnemyData[])formatter.Deserialize(fs);
    catch (SerializationException e)
        success = false;
        Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
    finally { fs.Close(); }   
    return success;


Also I found this recently which is probably the preferred way to do it if targeting xbox also:


and demo zip:


#5194166 Managing spritesheets

Posted by on 22 November 2014 - 02:34 PM

Difference being on how the spritesheet is put together - like if I made the animation cycle so that each frame is spaced equally apart so the animation module can simply change the source rectangle each frame by some even amount -- then I will use a bit more space on the sheet than if all the source rects were packed tightly together(in which case I couldn't use the same technique and would therefore need precise locations for all the animation frames). I guess this wouldn't be an issue if all your animation frames were close to the same size, however if your character is doing really crazy things in each frame it may be easier to use a sprite sheet packer to assemble the sheet and rectangle definitions for you.

  For more compression (data compression) you could use a DXT type compression in video memory. I know in XNA it is just a matter of changing the properties of the texture in the content pipeline but I'm not sure how it is done otherwise. DXT is lossy so is good for background stuff but I don't know if I recommend it for characters that you will see in front of you all the time if a crisp vibrant image is important to you.

Good luck on your project :)

#5193715 Managing spritesheets

Posted by on 19 November 2014 - 09:55 PM

I'm agreeing with unbird - also I'd say it depends on how much animation data you end up with. Originally for animated characters, I used even rows for each animation (walk row, run row, jump row, etc... ) but I added tons and tons of animations and started hogging the video ram with numerous 4086x4086 sheets. I found a compressed atlas worked better. The only tricky part then is getting the program to recognize which rectangle sections belong to which animation. If you put each animation frame from your sheet on a separate layer in your image editor and use an export layers to files option (however you do it in your editor) - ie: layers: walk1, walk2, walk3, etc... then use a utility like: Sprite Sheet Packer or something similar which will export a space-saving sprite-sheet as well as a .txt file containing all the rectangles. You can parse the .txt file and use the corresponding names and numbers to automatically match up the animation frames to their place on the sheet and save a lot of video ram (and manual work).  

That being said, however, either approach is good for your purposes I think. Only would be necessary to do it that way if video-ram becomes a concern.

#5193563 Orthographic Projection, width/height

Posted by on 19 November 2014 - 12:07 AM

Maybe change this:

projection = Matrix.CreateOrthographic(Width,Height,near,far);

to something like this:

projection = Matrix.CreateOrthographicOffCenter(left,right,bottom,top,near,far);

Where left is 0, right is width, bottom is height and top is 0 and near could be say -2000 and far +2000 if you really wanted..

Also good to translate the projection -0.5 up and -0.5 left to get good pixel alignment (could just leave view as identity and use a world matrix to move scene)

#5190524 2D game Terraria-like lighting

Posted by on 01 November 2014 - 02:14 AM

I think you'd do like with light intensity but the same technique applied to all 3 channels of the color: red_level, green_level, blue_level.. One other thing you can try to speed up the algorithm, is to not finish all the lighting calculations every frame. In other words, you do enough to keep up to a desired accuracy rate in each loop (keeping track of where you left off and perhaps even focusing first more on tiles where changes occurred) and then have the alg continue where you left off in the calculations in the next loop. I don't know if I'm right but I suspect this self-correcting style of lighting might not have any distracting artifacts. It's an idea anyway.

#5190348 Faster 2D Lens Flare Occlusion Fade

Posted by on 31 October 2014 - 07:05 AM

Aha! I got Method 5 working (just using spriteBatch) and the performance is excellent and the fade-out looks great.

I noticed one thing weird, the foreground needed to use an alpha test (otherwise transparent pixels would have depth and be considered occluding) - but the odd thing was that when I applied the alpha test, the depth values had to go from ( 0f  to  -1.0f ) instead of ( 0f  to +1.0f )... but all other rendering still must be 0-1... what the.....?


Oh well, at least it works! Here's how it looks:


#4997297 2d collisions

Posted by on 04 November 2012 - 03:21 PM

Not sure which types of collision detection would be most useful to you. If you're doing 2d tile platformer these might help:
Types of tile based collision methods:
Pixel perfect collision detection:
Here you can find rectangle-based collision detection source code - also links to pixel-collision and others:

I'm thinking rectangle-rectangle collision detection works for most things (but may want to try bounding-circle [radius-overlap] for some things)

#3865299 D3DXMatrixMultiply implimentation?

Posted by on 02 January 2007 - 09:15 PM

Most impressive. :)