Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
That Turkey Story
Mar 30, 2003

SupSuper posted:

If only MSVC had full C++11 support. :negative:

I'm pretty sure that was one of the first things they supported, well before the standard was finalized.

Adbot
ADBOT LOVES YOU

Orzo
Sep 3, 2004

IT! IT is confusing! Say your goddamn pronouns!

seiken posted:

When you say you just keep an integer index into an array of matrices, you mean the array is in the shader so you don't have to switch state, right? I'm still pretty sure you shouldn't need to batch by view transformation.
No, I didn't mean that, but that's a pretty good idea!

This is how I use it:
1. Each 'section' has a 'view', which translates to a 4x4 Matrix.
2. The 'game' has a list of N 'sections'. A section is really a scene. Typical scenario is that Section 1 is a level that's scrolling away, Section 2 is a level that's scrolling in, Section 3 is the HUD.
3. The gather-render-items method loops over the sections. For each section, it calculates the 4x4 view matrix and assigns an index to it. It sets up the 'batcher' (the wrapper around my big dictionary) such that all subsequent 'add item' calls will use that number (0, 1, or 2) as the view index. The reason it's done this way instead of building N separate lists is because the 'view dictionary' isn't the top level dictionary.
4. So, the first section is rendered with view matrix 0, the second section is rendered with view matrix 1, etc.

I really like your idea of eliminating the extra batches by view! The only downside is that I'd have to send an extra byte (depending on how many views I want to support at once, I'm sure 256 is reasonable enough...) to the GPU per vertex.

Manslaughter posted:

Is there a reason you can't use a ref Matrix4?
No, but I'm sure the GetHashCode() calculation for Matrix4 is also more expensive than using an int. Since I know the matrixes ahead of time, using an indexer is quite easy.

seiken
Feb 7, 2005

hah ha ha

Orzo posted:

I really like your idea of eliminating the extra batches by view! The only downside is that I'd have to send an extra byte (depending on how many views I want to support at once, I'm sure 256 is reasonable enough...) to the GPU per vertex.

I'm by no means a graphics expert, but I think this is probably worth it. As I understand it state switches are ridiculously more expensive than anything else so it's worth eliminating them at pretty much any cost (plus a byte per vertex is basically nothing!)

Orzo
Sep 3, 2004

IT! IT is confusing! Say your goddamn pronouns!
But what am I going to do if I need to render 257 scenes at once?!?!?

Schmerm
Sep 1, 2000
College Slice
As someone told me in the Graphics Questions thread, it's best to profile your code with AMD/NVidia's tools before making assumptions about what's faster than what. Graphics drivers do all sorts of runtime optimizations. An extra uniform parameter change might stall the graphics pipeline, or it may not, less/more than a texture change. An extra byte attribute might cause your vertex data to lose favourable alignment in GPU memory, or if padded to alignment, cause bigger vertices and thus worse cache performance. And on top of that, none of this might matter at all unless you start dealing with tens of thousands of things to render per frame. Keep your code simple to write and debug at first, then profile and optimize later.

SupSuper
Apr 8, 2009

At the Heart of the city is an Alien horror, so vile and so powerful that not even death can claim it.

That Turkey Story posted:

I'm pretty sure that was one of the first things they supported, well before the standard was finalized.
The keyword is full support: http://msdn.microsoft.com/en-us/library/vstudio/hh567368.aspx

That Turkey Story
Mar 30, 2003


Yeah, I know. The chances of Microsoft ever fully supporting C++98, let alone C++11 are pretty slim, despite their more recent claims.

xgalaxy
Jan 27, 2004
i write code

That Turkey Story posted:

Yeah, I know. The chances of Microsoft ever fully supporting C++98, let alone C++11 are pretty slim, despite their more recent claims.

The CTP gets it fairly close. But still lacks constexpr and some other things, really hurts.

Paniolo
Oct 9, 2007

Heads will roll.
All I can say is, do whatever works for you in your personal projects, but declaring nested containers would be a spectacularly quick way of failing a programming test at most studios. And asking why you shouldn't do that would probably be a pretty good interview question...

Orzo
Sep 3, 2004

IT! IT is confusing! Say your goddamn pronouns!
I'm curious to hear your reasons. I'm guessing it has something to do with the cache performance compared to a flat array. All I know is that when done correctly, the performance hit in the nested dictionaries is not even close to the performance bottleneck.

Vinterstum
Jul 30, 2003

Orzo posted:

I'm curious to hear your reasons. I'm guessing it has something to do with the cache performance compared to a flat array. All I know is that when done correctly, the performance hit in the nested dictionaries is not even close to the performance bottleneck.

Cache performance and memory fragmentation issues (depending on the implementation details). There's usually a better way, even if it makes the initial implementation more complex.

EDIT: In your previous example, I'd be willing to bet that the O(n log n) hit of a per-frame in-place sort of a flat array would be faster than nested dictionaries.

Vinterstum fucked around with this message at 02:42 on May 30, 2013

KoRMaK
Jul 31, 2012



Orzo posted:

Just about every 2D graphics engine has some sort of layering and batching system to minimize state changes on the GPU. In my case, a state change is either (a) a texture change, (b) a blending mode change, or (c) a view transform change (I perform my view matrix calculations on the GPU and use a uniform for the matrix).
This just gave me insight into yet another way the principal of "states" can be applied.

What does "batch" and "batching system" mean? I think I've scene it in the Infiniminer source in regards to 2D sprites, but I'd like to know more.

Orzo
Sep 3, 2004

IT! IT is confusing! Say your goddamn pronouns!

Vinterstum posted:

Cache performance and memory fragmentation issues (depending on the implementation details). There's usually a better way, even if it makes the initial implementation more complex.

EDIT: In your previous example, I'd be willing to bet that the O(n log n) hit of a per-frame in-place sort of a flat array would be faster than nested dictionaries.
Gonna do some profiling and find out for sure. All of this talk has been useful! I'll be sure to report the results...although I'm going to be on vacation for a week, so it might be a while.

KoRMaK posted:

This just gave me insight into yet another way the principal of "states" can be applied.

What does "batch" and "batching system" mean? I think I've scene it in the Infiniminer source in regards to 2D sprites, but I'd like to know more.
Simply put, telling the graphics card to switch textures is expensive. That is, let's say you have two textures, apple and orange (A and O). If you draw A, O, A, OO, AAA, that's 5 texture switches counting the initial one. If, however, you order your list so that it's AAAAA and then OOO, that's only two texture switches. The grouping of similar items together is 'batching'--i.e. creating big batches of textures that the GPU can process all at once.

Batching is the reason why people create Texture Atlases, also sometimes known as sprite sheets. If we put the apple and orange, two 64x64 images, into one 128x64 image, then we can draw the ENTIRE set of things without any switches at all.

http://en.wikipedia.org/wiki/Texture_atlas

Switching textures isn't the only thing that's expensive. Changing blend modes, texture filtering modes, setting variables (uniforms) on shaders, etc, are all things that are 'expensive'.

KoRMaK
Jul 31, 2012



Oh so batching can go beyond just 2D applications. Say, a "glass" polygon with transparency, or even polygons of different textures.

Is that also a reason in the pro column to use sprite sheets instead of animated gifs? I've never scene an efficiency reason or otherwise for why to use one over the other. I prefer gifs.

Orzo
Sep 3, 2004

IT! IT is confusing! Say your goddamn pronouns!
Yes, batching has nothing to do with 2D. The same techniques apply to 3D, too.

GIFs are a pain in the rear end to manage, IMO. Any image editor or content pipeline worth using will have *some* way to visualize many frames--say, bmp or png--in a way that you might with a gif.

KoRMaK
Jul 31, 2012



Orzo posted:

GIFs are a pain in the rear end to manage, IMO. Any image editor or content pipeline worth using will have *some* way to visualize many frames--say, bmp or png--in a way that you might with a gif.
Meaning that while I'm working on a sprite sheet, I can quickly see what it would look like run together as an animation? What image editor is good for this? I'm using Photoshop and don't know of a feature that does this, except for the gif style animation stuff.

superh
Oct 10, 2007

Touching every treasure

KoRMaK posted:

Is that also a reason in the pro column to use sprite sheets instead of animated gifs? I've never scene an efficiency reason or otherwise for why to use one over the other. I prefer gifs.

Besides the benefit that spritesheets will give you batching in engines that draw 2d sprites as polygons, with gifs you are going to be limiting yourself to a 256 color palette per animation and the accompanying dithering associated with turning an image into that palette.

Besides that, not many frameworks will let you load up a gif and play it within the context of a game, that I know of? Are you using the gif timing for the animation timing, or timing it out yourself?

I actually can't think of any benefit to using animated gifs. There are many utilities out there that will take a series of images done in photoshop and pack them into an easily parseable atlas for your platform of choice - like http://www.codeandweb.com/texturepacker

Reiley
Dec 16, 2007


KoRMaK posted:

Meaning that while I'm working on a sprite sheet, I can quickly see what it would look like run together as an animation? What image editor is good for this? I'm using Photoshop and don't know of a feature that does this, except for the gif style animation stuff.

When I make sprite animations in Photoshop I'll grid off an area with guidelines (click the ruler and drag to where you want it to be) to create squares of my desired dimensions. When I animate I'll create and edit duplicate layers (ctrl+J copies a selection to a new layer and ctrl+shift+J cuts to a new layer) to save time, but I'll always keep the frame layers on top of each other in the same grid, this way I can open up the Animation window and run test cycles to see how fluid it is or what needs to be changed (I prefer Filmstrip mode to Timeline mode for Photoshop animation). Only after all the frames are done and fluid will I drag them over to separate squares in my grid to flatten out into a sprite sheet. You can also work on your frames side-by-side to rough them out- and in spite of what I just typed I'll sometimes do this- but when you start finalizing you'll want the layers positioned overtop one another so you can see how they cycle within the same sprite space. Working on separate layers is crucial so you don't have to keep importing sprite sheets into a game to see where your animation mistakes might be, and you can always flatten them out and re-separate them with ctrl+shift+J as needed.

Shalinor
Jun 10, 2002

Can I buy you a rootbeer?

Vinterstum posted:

Cache performance and memory fragmentation issues (depending on the implementation details). There's usually a better way, even if it makes the initial implementation more complex.

EDIT: In your previous example, I'd be willing to bet that the O(n log n) hit of a per-frame in-place sort of a flat array would be faster than nested dictionaries.
This is all true, and it also basically doesn't matter for most use cases. All the usual arguments against premature optimization apply. If his crazy nested classes work, then that makes sense, until it actually presents a bottleneck.

... though it definitely makes me cringe, regardless, for the aforementioned reasons.

ninjeff
Jan 19, 2004

Orzo posted:

code:
foreach(LayerType layerType in items.LayerTypes.Keys)
{
   gfx.SetLayerType(layerType); //might be a different shader or something
   var layersForThisLayerType = items[layerType];
   //Iterate over layers to ensure painters algorithm
   foreach(int layer in layersForthisLayerType.Keys)
   {
      var allBlendModes = layersForThisLayerType[layer];
      foreach(BlendMode blendMode in allBlendModes.Keys)
      {
        gfx.SetBlendMode(blendMode); //changes blending function
        var allTextures = allBlendModes[blendMode];
        foreach(Texture texture in allTextures.Keys)
        {
           gfx.SetTexture(texture); //changes texture
           foreach(List<RenderItem> itemBatch in allTextures[texture])
           {
             //Actually sent the vertices and draw triangles
             gfx.RenderBatch(itemBatch);
           }
        }
      }
   }
}

If you're iterating over everything in your dictionaries, it's almost certainly going to be faster to do it more like this (innermost dictionary only):
code:
foreach(var kvp in allTextures)
{
    gfx.SetTexture(kvp.Key); //changes texture
    foreach(List<RenderItem> itemBatch in kvp.Value)
    {
        //Actually sent the vertices and draw triangles
        gfx.RenderBatch(itemBatch);
    }
}
I'm not 100% sure, but I think that pretty much reads out the entries in order as they're stored, turning your O(n log n) into O(n).

Edit: I'm dumb, indexing into a Dictionary is O(1)

ninjeff fucked around with this message at 09:47 on May 30, 2013

the
Jul 18, 2004

by Cowcaster
I made a particle system in Unity using the legacy particle system (I'm following a tutorial). However, the particle system is just magenta squares, and I can't set a color. What's going wrong here?

Mata
Dec 23, 2003
I use a lot of hardware instancing and have to batch my renderables by what model they're an instance of, then by texture atlas. For example the leaves in my trees are just a quad with a texure but can't be batched together with any other 'billboard sprites' because they don't share the same group of textures.
I'm having major alpha channel / sprite sorting issues though as you can see in these trees:


ninjeff posted:

Edit: I'm dumb, indexing into a Dictionary is O(1)
What? You mean OrderedDictionary?
Nevermind I just looked it up, I thought dictionary lookups were log n..

Mata fucked around with this message at 18:20 on May 30, 2013

Stiggs
Apr 25, 2008


Miles and miles of friends!

the posted:

I made a particle system in Unity using the legacy particle system (I'm following a tutorial). However, the particle system is just magenta squares, and I can't set a color. What's going wrong here?

Are you using your own texture for it? If so, make sure to set the materials shader or whatever to 'Particles/...'.

the
Jul 18, 2004

by Cowcaster

Stiggs posted:

Are you using your own texture for it? If so, make sure to set the materials shader or whatever to 'Particles/...'.



Um... I'm not sure how to get that? I have been following this video, and someone earlier in this thread said to make what he has I need to make an empty gameobject and add in Ellipsoid Particle Emitter, Particle Renderer, and Particle Animator. I did that, and I have the same animation as him now, but my particles look like giant magenta squares and changing the colors in the Particle Animator window does nothing.

EDIT: I've gotten it to be "not magenta" by going into the Particle Renderer --> Materials --> Element 0 and selecting "Default-Particle" which gives me some block shapes, but those still aren't colored by the Particle Animator tab.

EDIT: Wait, it worked!

the fucked around with this message at 21:10 on May 30, 2013

Vinterstum
Jul 30, 2003

Shalinor posted:

This is all true, and it also basically doesn't matter for most use cases. All the usual arguments against premature optimization apply. If his crazy nested classes work, then that makes sense, until it actually presents a bottleneck.

... though it definitely makes me cringe, regardless, for the aforementioned reasons.

Makes for a good interview question though!

Dr. Dos
Aug 5, 2005

YAAAAAAAY!
I just realized tomorrow is June 1st and I haven't seen a thread about another SA Game Dev Challenge. Are they over and done with? :ohdear:

xzzy
Mar 5, 2009

Dr. Dos posted:

I just realized tomorrow is June 1st and I haven't seen a thread about another SA Game Dev Challenge. Are they over and done with? :ohdear:

Tomorrow is May 31st in the US. :ssh:

Hemingway To Go!
Nov 10, 2008

im stupider then dog shit, i dont give a shit, and i dont give a fuck, and i will never shut the fuck up, and i'll always Respect my enemys.
- ernest hemingway
I'm doing some self-teaching on game coding over the summer.

I recently read this article about how a puzzle game developer made an interesting system for viewing the state space of a puzzle.

What would be the best language for whipping something like that up? Basically something capable of gui features and simple, manipulable graphics.

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!
HTML5 would be good for that, but probably not so hot on the "usefully save/load" aspect of things. (I knocked up a "convert database schema file into well arranged graph diagram with additional information mouseovers" thing in a couple of hours, probably quicker than it would have been to just draw the diagram by hand. HTML5 is great for diagram-type output because the canvas has all the line functions and poo poo that you used to get in basic languages, with hardly any of the setup poo poo you have to do for your opengl, directx or windowing-system-API.)

roomforthetuna fucked around with this message at 02:22 on May 31, 2013

A Bloody Crowbar
May 9, 2009

This is AS3/Flixel.
I'm trying to load an array for a tile map from an external file. Eventually I'm hoping to combine this with some PHP scripting for a very basic online level editor, but for now I'm just working locally.
code:
package
{
	import flash.events.*;
	import flash.net.*;
	
	import org.flixel.*;
	
	public class PlayState extends FlxState
	{	
		private var _level:FlxTilemap;
		
		override public function create():void
		{
			FlxG.mouse.show();
			_level.loadMap(FlxTilemap.arrayToCSV(getData(), 20), FlxTilemap.ImgAuto, 0, 0, FlxTilemap.AUTO);
			add(_level);
		}
		
		private function getData():Array
		{
			var data:Array = new Array();
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(ProgressEvent.PROGRESS, onProgress);
			function onProgress(e:ProgressEvent):void
			{
				FlxG.log("LOADED:"+e.bytesLoaded+"/"+e.bytesTotal);
			}
			loader.addEventListener(Event.COMPLETE, onLoad);
			function onLoad(e:Event):void
			{
				//FlxG.log("SUCCESS:"+e.target.data);
				data = e.target.data.split();
				FlxG.log(data);
			}
			loader.load(new URLRequest("../data/default.txt"));
			return data;
		}
	}
}
I'm assuming data is being returned before the completion handler does its work.
It may just be because it's almost 4am but I'm lost as to how I can wait until that handler finishes before returning anything in the outer method...

superh
Oct 10, 2007

Touching every treasure

A Bloody Crowbar posted:

This is AS3/Flixel.

I'm assuming data is being returned before the completion handler does its work.
It may just be because it's almost 4am but I'm lost as to how I can wait until that handler finishes before returning anything in the outer method...

Yeah, you're returning the null data object instantly because the load hasn't completed by the time the function ends. The onLoad event hasn't fired yet. Flash isn't threaded so you can't like, force a wait in that function until it's done or the whole program will halt waiting for the load. Do this instead:

code:
public class PlayState extends FlxState
{	
	private var _level:FlxTilemap;
	public var data : Array;
	public var loadComplete : Bool;
		
	override public function create():void {
		FlxG.mouse.show();
		_level.loadMap(FlxTilemap.arrayToCSV(getData(), 20), FlxTilemap.ImgAuto, 0, 0, FlxTilemap.AUTO);
		add(_level);
	}
		
	private function getData():void {
		data = new Array();
		loadComplete = false;
		var loader:URLLoader = new URLLoader();
		loader.addEventListener(ProgressEvent.PROGRESS, onProgress);
		function onProgress(e:ProgressEvent):void {
			FlxG.log("LOADED:"+e.bytesLoaded+"/"+e.bytesTotal);
		}
		loader.addEventListener(Event.COMPLETE, onLoad);
		function onLoad(e:Event):void {
			//FlxG.log("SUCCESS:"+e.target.data);
			data = e.target.data.split();
			loadComplete = true; // Set this to true when it's done, it will be at an unknown time
			FlxG.log(data);
		}
		loader.load(new URLRequest("../data/default.txt"));
		// Don't return the data here!
	}
}
So then, wherever you call doLoad() from, loop and do something else but check whether or not the loadComplete is done and it's safe to use the data variable.

Met48
Mar 15, 2009
If you need useful save/load for an HTML5 app, node-webkit is a good option. You could then use the node.js filesystem functions.

Stiggs
Apr 25, 2008


Miles and miles of friends!
I am struggling with collision detection in my little 2d tile based game. :(

I didn't really know where to begin, so I looked at the Platformer starter kit for XNA and pretty much just used that. And it works, but there is a point in between the tiles where if you land there, the thing that is colliding with that tile snaps 8 or so pixels to the right.

That was a terrible explanation, so here's a video!

https://www.youtube.com/watch?v=X78-Os_A5_8

This is the 'RectExtension' class.

code:
    public static class RectExtension
    {
        public static Vector2 getIntersect(Rectangle a, Rectangle b)
        {
            // Half extents.
            float halfWidthA = a.Width / 2.0f;
            float halfHeightA = a.Height / 2.0f;
            float halfWidthB = b.Width / 2.0f;
            float halfHeightB = b.Height / 2.0f;

            // Calculate centers.
            Vector2 centerA = new Vector2(a.Left + halfWidthA, a.Top + halfHeightA);
            Vector2 centerB = new Vector2(b.Left + halfWidthB, b.Top + halfHeightB);

            // Calculate current and miminum non-intersecting distance between centers.
            float distX = centerA.X - centerB.X;
            float distY = centerA.Y - centerB.Y;
            float minDistX = halfWidthA + halfWidthB;
            float minDistY = halfHeightA + halfHeightB;

            // If there is no intersection, return 0.
            if (Math.Abs(distX) >= minDistX || Math.Abs(distY) >= minDistY)
                return Vector2.Zero;

            // Calculate and return intersection depth.
            float depthX = distX > 0 ? minDistX - distX : -minDistX - distX;
            float depthY = distY > 0 ? minDistY - distY : -minDistY - distY;

            return new Vector2(depthX, depthY);
        }
    }
And here is where I actually detect collisions.

code:
private void HandleCollisions()
        {
            Rectangle bounds = boundingRect;

            int leftTile = (int)Math.Floor((float)bounds.Left / Tile.Width);
            int rightTile = (int)Math.Floor(((float)bounds.Right / Tile.Width));
            int topTile = (int)Math.Floor((float)bounds.Top / Tile.Height);
            int bottomTile = (int)Math.Floor(((float)bounds.Bottom / Tile.Height));

            for (int x = leftTile; x <= rightTile; x++)
            {
                for (int y = topTile; y <= bottomTile; y++)
                {
                    TileCollision collision = level.GetCollision(x, y);

                    if (collision != TileCollision.Passable)
                    {
                        // Find out the collision depth and direction.
                        Rectangle tileBounds = level.GetBounds(x, y);
                        Vector2 depth = RectExtension.getIntersect(bounds, tileBounds);

                        if (depth != Vector2.Zero) // If there is actually a collision...
                        {
                            absDepthX = Math.Abs(depth.X);
                            absDepthY = Math.Abs(depth.Y);

                            if (absDepthX > absDepthY)
                            {
                                position = new Vector2(position.X, position.Y + depth.Y);
                                bounds = boundingRect;
                            }
                            else
                            {
                                position = new Vector2(position.X + depth.X, position.Y);
                                bounds = boundingRect;
                            }
                        }
                    }
                }
            }
        }
If anyone could help me out here I would appreciate it a lot!

Or if this is a bad way of handling collisions, I'd be happy to hear suggestions for other methods!

Orzo
Sep 3, 2004

IT! IT is confusing! Say your goddamn pronouns!
Before giving up, I highly recommend figuring out a way to set a breakpoint at the moment of the first collision after jumping and then stepping through your process from there. C#/Visual Studio has excellent debugging functionality, learning to use effectively is critical.

In case you're not familiar, here's a quick crash course:
1. Set a breakpoint on any line with F9, or by clicking the bar to the left of your code.
2. Right click the breakpoint and set a condition.
2a. Alternatively, because (2) can be slow, I just a block of code to the place I'd normally do (2):
code:
if (myConditionForTriggeringBreakpoint)
{
  int x = 1; //Set breakpoint here
}
3. Hit F5 to run in debug mode. When your breakpoint hits, use F10/F11 to step over/in to code.
4. Hover over variables or use the locals window to look at stuff. Use the immediate window to type in whatever the hell you want--either to print out values of local variables or execute commands.

Orzo fucked around with this message at 15:47 on May 31, 2013

Stiggs
Apr 25, 2008


Miles and miles of friends!

Orzo posted:

Before giving up, I highly recommend figuring out a way to set a breakpoint at the moment of the first collision after jumping and then stepping through your process from there. C#/Visual Studio has excellent debugging functionality, learning to use effectively is critical.

In case you're not familiar, here's a quick crash course:
1. Set a breakpoint on any line with F9, or by clicking the bar to the left of your code.
2. Right click the breakpoint and set a condition.
2a. Alternatively, because (2) can be slow, I just a block of code to the place I'd normally do (2):
code:
if (myConditionForTriggeringBreakpoint)
{
  int x = 1; //Set breakpoint here
}
3. Hit F5 to run in debug mode. When your breakpoint hits, use F10/F11 to step over/in to code.
4. Hover over variables or use the locals window to look at stuff. Use the immediate window to type in whatever the hell you want--either to print out values of local variables or execute commands.

Thanks, what seems to be happening is that it is still colliding with the tile to the left and the X intersection is smaller than the Y intersection on that tile, so it pushes it along the X axis instead of the Y.

Now to figure out how to actually fix it. :)

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!

Stiggs posted:

Now to figure out how to actually fix it. :)
One fairly simple way would be to check if there is a tile in the direction you're going to push the player out in. Since there's no benefit to pushing the player right if there is another block tile to the right, he's just going to be crushed between tiles until you push him up, so you might as well just push him up.

And if there's a tile in both directions then 'this tile' doesn't need to do anything at all because both of those tiles will be pushing the player out (unless you've got your steps way too big).

poemdexter
Feb 18, 2005

Hooray Indie Games!

College Slice
Having gone down this road more than once, I highly recommend you start breaking your already small methods into even smaller methods and start commenting liberally. This will keep you from tearing your hair out in frustration from tiny "what ifs" as they spring up as well as prevent the "deer in the headlights" look when you come back a week later and see nothing but X and Y everywhere and no idea how it all came to be.

Stiggs
Apr 25, 2008


Miles and miles of friends!
Thanks guys, I've got it working a little better now. Before it was looping through every tile that it was touching, so when you were in between two tiles it was still getting the intersect depth of the tile to the bottom left of the player, so when the X intersect of the bottom left tile was small enough, it just pushed you to the right.

I've changed it so that it will only push you along the X axis if there are tiles directly to the left or directly to the right.

This fixed the issue I was originally having, but now the same sort of thing is happening when you hit a tile from the bottom while jumping into it. One step at a time! :v:

poemdexter posted:

Having gone down this road more than once, I highly recommend you start breaking your already small methods into even smaller methods and start commenting liberally. This will keep you from tearing your hair out in frustration from tiny "what ifs" as they spring up as well as prevent the "deer in the headlights" look when you come back a week later and see nothing but X and Y everywhere and no idea how it all came to be.

Yeah I definitely need to get better at commenting my code. I will keep this in mind.

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!

Stiggs posted:

I've changed it so that it will only push you along the X axis if there are tiles directly to the left or directly to the right.
If this was based on my suggestion then you misunderstood.
What I meant was check like
code:
if (tile_at(x,y).IsABlock()) { //this line is whatever you're already doing
  if (RightPushSize()<UpPushSize() //again I figure you're already doing this
      && tile_at(x+1,y).IsNotABlock()) { //this is the additional check
    PushRight();
  } else {
    PushUp();
  }
}
The idea being that you shouldn't push the player out in a direction that is also blocked.
Obviously this shouldn't just be right and up, it should be whatever direction X and Y adjustments, and the blocked-check should be adjusted to the appropriate directions, this is just the concept.

Edit: Also, x and y in this pseudocode are the tile coordinates, not the pixel coordinates.

roomforthetuna fucked around with this message at 20:37 on May 31, 2013

Adbot
ADBOT LOVES YOU

Schmerm
Sep 1, 2000
College Slice
Here's a nonportable way I use to generate temporary breakpoints, that works only on x86:

code:
if (some condition)
{
    __asm int 3;
}
This generates a software interrupt using inline assembly and will make the debugger break there.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply