Alex Kovar

Alex Kovar

Software Engineer

© 2020

A Simple Implementation Of A Cat And Mouse Game

I spent some time revisiting an old project that I worked on long ago. It wasn’t anything productive, just a small game where you chase a ball using the mouse.

As I have been doing some playing around with algebra lately, I decided it would be fun to rewrite it and simplify the logic a little bit and then write this post to explain it.

At any point in time, there are three points: the mouse, the point where the ball is located, and the center of the grid. These can be viewed as vectors starting from the origin (0, 0).

\frac{-b\pm\sqrt{b^2-4ac}}{2a}

To calculate the vector that points from the mouse to the ball, you simply need to subtract those two vectors: m - b

\frac{-b\pm\sqrt{b^2-4ac}}{2a}

This will give you the ‘escape vector’, I.E. the direction that the ball needs to go in order to ‘escape’ the mouse. We can use this vector to determine the next location of the ball by adding it to the current vector: b + escapeVector

The only problem is that the length of vector gets smaller as the mouse approaches the ball. This is not really the desired effect because if anything, we would want the ball to move even faster as the mouse approaches it. So the direction of the vector is correct, but the magnitude is not. To solve this, we can convert this vector into a unit vector:

\frac{-b\pm\sqrt{b^2-4ac}}{2a}

This gives us a vector in the same direction with a length of 1. We now simply need to multiply this unit vector by the correct multiplier. So what is the correct multiplier? One way to achieve it would be to subtract the length of the escape vector by some constant. We don’t want the ball to go too far, otherwise it will leave the grid. This can gives us a clue about what this constant can be. Let’s try the length of the center vector to be this constant. This way, if the