I am recreating Pacman in my class, and I encountered a problem making the ghosts collide with Pacman using corner collisions, so I was told to make a function that calculated the distance between the ghosts and Pacman, and use a "radius" to see if they are within colliding distance. My calculation code goes as follows:
When I run it, the ghosts just move through Pacman, and when I debug it and hover over p.center.x, it doesn't show the value, nor does it show the value for difference.x, difference.y, cSquared, or distance.
If this returns true, I lose a life and get reset. If it returns false, nothing happens. If Pacman is powered up, it resets the ghost's position to the start and gives me points.
It's just a bool variable. This worked when I was checking just the corners (except a certain area at the top, which is why I am changing the collision detection)
You store the distance in a local variable inside doMath so when the function ends the calculations will be lost. You will have to return or store the distance in a variable that you can use after the function has return. If Ghost has a distance member variable that you want to get this value it is as simple as just removing the float from line 10.
If you are not going to use the value of difference in any other parts of your code you could make difference a local variable and remove the if statements on lines 5-8 because the sign will disappear when you calculate the square anyway (multiply two negative numbers and you get a positive number).
So, now I am returning true if the distance is less than 7, and false if it is not, and the code is causing some problems.
The space I've circled in red is the only place I seem to be able to collide with the ghosts. And sometimes it's when I'm half way down the hall. Also, it's ONLY when I'm below them.
Apparently I can't post links. Anyways, it is only in one hallway, and it is only when I am below them.
This method of collision checking is called "bounding sphere" and it's perfectly acceptable. It's usually used as a first pass over a list of objects before a more precise method to cull object pairs that couldn't possibly be intersecting, but it can be used on its own if only approximate detection is enough for the application.
The function appears correct, as well. If you're getting weird behavior it's likely because you're not using the function properly. Either you're not properly filling the variables that the function uses (there's probably some uninitialized variables), or you're not correctly using the return value from the function.