Saturday, August 11, 2018

Collisions

So, I'm working on the boss fight for the "Polygon of Horror" where the boss and the shield generators have shields up part of the time. The player ship needs to bounce off of them. Since this is a twin stick shooter and not a platformer, collision detection and behavior need not be complex. In fact, it needs to be simple.
And it has been up to now. Simple, but tedious. On wall collisions, the player object was literally checking to see which wall object it was hitting and then acting accordingly. This involved putting "left" walls on the left of the room, "bottom" wall on the bottom of the room and so on.

It was not, how you say in America, a general solution.

Well, for a round object like a shield, this is obviously not going to work, so I had to come up with something else. And I did:
//get the center of the object I just collided with
px =other.x
py =other.y

//get the difference in position between my center and that of the object
tx = x - px;
ty = y - py;
//get the sign of that difference
sx = sign(tx);
sy = sign(ty);
//get the X to Y ratio of the line between the two points
//in absolute terms
ar = abs(tx/ty);
at = abs(ty/tx);

//assign a new location "15" ish pixels from the collision in the opposite direction
x += sx * (min(15, 15 * ar))
y += sy * (min(15, 15 * at));
//YAY, no trigenometry

When the player collides with an object now, I run the above and it bounces 15 or so (will tweak it later) pixels in the opposite direction. I could probably get it down to like 4 lines of code, but this is actually readable.


 Next, I created a single collidable wall object (instead of four) and surrounded the room with it:
 Those grey blocks (which are invisible at run time) are all identical, and the code to deal which each is exactly the same. Th exact same code is used on the shields in the boss level:
This also means that I can finally get around to having the player ship actually collide with the enemy spawners (to their detriment)