Game Development Reference
In-Depth Information
3. If the distance between ball and player equals the sum of the radii of both sprites,
or is less than the sum of the radii of both sprites, we have a collision:
if (distance1 <= squared_radii ||
distance2 <= squared_radii) {
4. We use the squared radii values so we don't need to use costly square root calcula-
tions to get the values for distance. So all values in the previous conditional state-
ment are squared, including the distances.
5. These conditions are checked both with the player's current position and its next
position, so there is less risk of the ball moving "through" the player sprite
between iterations.
6. If there is a collision, we grab the magnitudes of both the ball's vector and the
player's vector, and make the force with which the ball will be pushed away. We
update the ball's next position in that case, and play a nice sound effect through
the SimpleAudioEngine singleton (don't forget to include the SimpleAu-
dioEngine.h header file and declare we're using the CocosDenshion
namespace):
float mag_ball = pow(ballVector.x, 2) +
pow(ballVector.y, 2);
float mag_player = pow(playerVector.x, 2) + pow
(playerVector.y, 2);
float force = sqrt(mag_ball + mag_player);
float angle = atan2(diffy, diffx);
ballVector.x = force * cos(angle);
ballVector.y = (force * sin(angle));
ballNextPosition.x = playerNextPosition.x +
Search WWH ::




Custom Search