What I learned in creating a collision engine pt-3

Two thirds of the way through this saga we have an avatar that moves around a screen, bumps into the edges of the screen, and has a single object that it “knows” is there and bumps into.

The last part of this is the most epic! For those of you who’ve stayed with me it’s been worth the wait. Remember in part 2 where I said ignore the forEach and objectArray part? Ignore them no longer. This is where I discovered how to work with a node-list, queryselectorAll, and making a class of objects dynamically follow a rule set based on their CSS class.

The code I’m proud to present you looks like this.

Okay…. so I’m at least not THAT ashamed of it. What’s going on here? Top down, the queryselectorAll is collecting a node list from the DOM. It’s reading through every element that has the class of ‘solid’ and adding them to the list. Then for each element it’s defining all four sides in a 2d plane, and saving the sides as an object inside of an array.

Now if you remember this function, what’s going on here makes a little bit more sense. It’s evaluating every situation where the avatar is within moving distance of an object (4px) and if it is, is any part of it on a collision course for the other object? If this is all true. Stop right here and return the value false because we don’t want that to happen. (Because of how the decision logic tree I built for use cases work I assigned the false value to the variable value, which is declared in the parent function)

So now whenever I add any object into my avatars little world, and give it the class of solid. It’s dynamically added to the array of solidElements, it’s sides are defined in an object, and then whenever the avatar could ‘magic’ through the object the logic circuit stops and says it can’t move. I dynamically enforced the second law of physics in a computer.

This project took me a long time to do. I learned so much doing it. I appreciate you reading along with my journey. If there’s something I touched on and didn’t explain well enough, or if there’s something else you want to learn about, throw a response! I’ll be glad to help you learn.

A software engineer living in lonely world! He took the midnight train going anywhere.