## The Slopes

And now I give you SLOPE TILES!!! Check out these spectacular collision objects and how they clearly make even this extremely lame level more fun to play with than the last one. That probably has something to do with the fact that the level doesn't have any conflicting collision surfaces as well as the awesomeness of sloping tiles. So, give it a go! Click or double tap to jump!

So, one of the coolest features of this collision technique is that you can basically do whatever you want in the context of tiles. For example, those three solid slope tiles in the example have collision on 3 sides. There aren't many games out there that I've seen that implement stand alone slope tiles without a physics engine, and who has time to learn math and code a physics engine? Take a look at the source code to see how I did it. You could easily make it so that none of the red square overlaps the tile, but I like my red square to fall off once his mid point is off one side of the tile.

Anyway, there's not a whole lot to cover in this tutorial because nothing has really changed since the last one. All I did was add a few more collision methods to handle slopes and the code isn't that much different from a regular flat surface. Collision for a sloped surface looks like this:

function collideSlopeTop( object_, start_x_, start_y_, slope_ ){ /* b = y - mx */ var y_intercept = start_y_ - slope_ * start_x_; /* y = mx + b */ var top = slope_ * ( object_.x + object_.width * 0.5 ) + y_intercept; if ( object_.velocity.y >= 0 && object_.x + object_.width * 0.5 >= start_x_ && object_.x + object_.width * 0.5 <= start_x_ + tile_width && object_.y + object_.height > top ){ object_.y = top - object_.height; object_.velocity.y = 0; } }

That's a pretty big if statement, so, let's break it down in layman's terms: if the object is moving down or not moving at all on the y axis and the object's middle x coordinate is greater than or equal to the tile's left side and the object's middle x coordinate is less than or equal to the tile's right side and the object's bottom coordinate is greater than the top of the tile... Then you have a collision. Still pretty drawn out, but it works like a charm. As for the top and y_intercept variables, you should remember them from algebra. y = mx + b is literally how to find the y coordinate of a given x on a sloped line, which is conveniently just what we're doing. b is the y intercept of the line in the Cartesian coordinate system. Just a side note, the y axis of the Cartesian coordinate system is reversed in HTML, so up is negative rather than positive.

I don't think I can explain much further than that. The code is right there, so have at it. Look up how to use y = mx + b, you'll find a ton of reading material. As for the rest of this example's code, you can find that in the source, and I encourage you to follow that link at the bottom of the page to read it!

Collision Source Scrolling