Reputation: 733
I am having trouble understanding some of the math in the following tutorial:
I am not sure how to comprehend offset. About half way through the tutorial, Ray uses the following code:
UITouch * touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
// 2 - Set up initial location of projectile
SKSpriteNode * projectile = [SKSpriteNode spriteNodeWithImageNamed:@"projectile"];
projectile.position = self.player.position;
// 3- Determine offset of location to projectile
CGPoint offset = rwSub(location, projectile.position);
where rwSub is
static inline CGPoint rwSub(CGPoint a, CGPoint b) {
return CGPointMake(a.x - b.x, a.y - b.y);
}
I know this code works, but I don't understand it. I tried NSLogging the touch point and the offset point, and they do not form a triangle like it shows in the picture:
(source: raywenderlich.com)
This is what I got from my output:
Touch Location
X: 549.000000 Y: 154.000000
Offset
X: 535.500000 Y: -6.000000
This does not form a vector in the correct direction..but it still works? Is anyone able to explain how the offset works?
Upvotes: 1
Views: 556
Reputation: 19946
Offset is the difference from the ninja, and the point you have touched. So the touch you logged is, 535 pts to the right, and 6 pts down (-6).
So it is going in the correct direction, relative to the player.
The tutorial also forces the ninja star to travel offscreen, via
// 6 - Get the direction of where to shoot
CGPoint direction = rwNormalize(offset);
// 7 - Make it shoot far enough to be guaranteed off screen
CGPoint shootAmount = rwMult(direction, 1000);
// 8 - Add the shoot amount to the current position
CGPoint realDest = rwAdd(shootAmount, projectile.position);
Draw some pictures, it will help you understand.
Upvotes: 2
Reputation: 699
The offset in this case simply represent the location of the touch related to the character, and allow you to know where the projectile will be aimed.
In the tutorial, on the next lines you can see :
// 4 - Bail out if you are shooting down or backwards
if (offset.x <= 0) return;
In this example offset.x < 0
means that the projectile is targeting something behind the ninja on the x axis, where 0 is the x-coordinate of the character.
The idea here is to translate the projectile's target coordinates in the character's own referential to understand better their positions to each other.
Upvotes: 1