Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Bill Walker
5,951 PointsDivide by zero bug in "Shooting projectiles using SKAction"
I just finished up the "Actions and Animations" section of the "Build a Game with SpriteKit" course and while playing around with the game, I noticed that on occasion the projectile didn't appear to be firing, but the node count continued rising (and wouldn't go down).
Looking over the code in -(void)moveTowardsPosition:(CGPoint)position, I found the line that calculates the slope to be the problem:
float slope = (position.y - self.position.y) / (position.x - self.position.x);
If the user touches in the exact same x position as the projectile is located at, this causes division by zero. Instead of a crash, the code sets slope to negative or positive infinity. You can see this by setting a breakpoint on the line, and changing (position.x - self.position.x) to 0.
I would think something like this would be pretty rare for a user, but it happened to me consistently enough that it caused me to take a look. Unfortunately, I'm not too sure on how to fix it ;)
1 Answer
Patrick Cooney
12,216 PointsI haven't done that project yet or looked at the code. Could you just put in a simple if statement?
float xCoords = position.x - self.position.x;
float slope = (position.y - self.position.y) / xCoords;
if(xCoords != 0){
//I *believe* break should kick you out to the next instruction so you don't have
//to put huge amounts of code in your if statement
break;
} else {
//ignore input or handle error
}
Robert Bojor
Courses Plus Student 29,439 PointsRobert Bojor
Courses Plus Student 29,439 PointsAdding an if statement should prevent the problems I believe. Haven't reached this part yet but I'd go with a xCoords > 0 just to be sure, since it's illogical to shoot downwards.
And move the slope calculation inside the if statement.
Patrick Cooney
12,216 PointsPatrick Cooney
12,216 PointsWas thinking about that last night after I posted my answer. As I mentioned, I haven't gotten to this one yet (not terribly interested in games programming, tbh) so I wasn't sure if the game mechanics allowed you to shoot in any direction or not. Didn't want to limit the shooting direction if it shouldn't have been.
Bill Walker
5,951 PointsBill Walker
5,951 PointsI'll try this after I get home from work.
Thanks!