ios - Spritekit - How to calculate the distance between two nodes? - ios

I have two sknodes on the screen. What is the best way to calculate the distance ('as the crow flies' type of distance, I don't need a vector etc)?
I've had a google and search on here and can't find something that covers this (there aren't too many threads on stackoverflow about sprite kit)

Here's a function that will do it for you. This is from an Apple's Adventure example code:
CGFloat SDistanceBetweenPoints(CGPoint first, CGPoint second) {
return hypotf(second.x - first.x, second.y - first.y);
}
To call this function from your code:
CGFloat distance = SDistanceBetweenPoints(nodeA.position, nodeB.position);

Another swift method, also since we are dealing with distance, I added abs() so that the result would always be positive.
extension CGPoint {
func distance(point: CGPoint) -> CGFloat {
return abs(CGFloat(hypotf(Float(point.x - x), Float(point.y - y))))
}
}
Ain't swift grand?

joshd and Andrey Gordeev are both correct, with Gordeev's solution spelling out what the hypotf function does.
But the square root function is an expensive function. You'll have to use it if you need to know the actual distance, but if you only need relative distance, you can skip the square root. You may want to know which sprite is closest, or furtherest, or just if any sprites are within a radius. In these cases just compare distance squared.
- (float)getDistanceSquared:(CGPoint)p1 and:(CGPoint)p2 {
return pow(p2.x - p1.x, 2) + pow(p2.y - p1.y, 2);
}
To use this for calculating if any sprites are within a radius from the center of the view in the update: method of an SKScene subclass:
-(void)update:(CFTimeInterval)currentTime {
CGFloat radiusSquared = pow (self.closeDistance, 2);
CGPoint center = self.view.center;
for (SKNode *node in self.children) {
if (radiusSquared > [self getDistanceSquared:center and:node.position]) {
// This node is close to the center.
};
}
}

Swift:
extension CGPoint {
/**
Calculates a distance to the given point.
:param: point - the point to calculate a distance to
:returns: distance between current and the given points
*/
func distance(point: CGPoint) -> CGFloat {
let dx = self.x - point.x
let dy = self.y - point.y
return sqrt(dx * dx + dy * dy);
}
}

Pythagorean theorem:
- (float)getDistanceBetween:(CGPoint)p1 and:(CGPoint)p2 {
return sqrt(pow(p2.x-p1.x,2)+pow(p2.y-p1.y,2));
}

Related

Scaling a UIView along one direction with UIPinchGestureRecognizer

In my app I have a draggable UIView to which I have added a UIPinchGestureRecognizer. Following this tutorial, as default the view is scaled along both x and y directions. Is it possibile to scale along only one direction using one finger? I mean, for example, I tap the UIView both with thumb and index fingers as usual but while I'am holding the thumb I could move only the index finger in one direction and then the UIView should scale along that dimension depending on the direction in which the index moves.
Actually, I have achieved this by adding pins to my UIView like the following:
I was just thinking my app might be of better use using UIPinchGestureRecognizer.
I hope I have explained myself, if you have some hints or tutorial or documentation to link to me I would be very grateful.
In CGAffineTransformScale(view.transform, recognizer.scale, recognizer.scale) update only one axis: X or Y with recognizer.scale and keep the other one 1.0f
CGAffineTransformMakeScale(CGFloat sx, CGFloat sy)
In order to know which axis you should scale, you need to do some math to see the angle between two fingers of a gesture and based on the angle to decide which axis to scale.
Maybe something like
enum Axis {
case X
case Y
}
func axisFromPoints(p1: CGPoint, _ p2: CGPoint) -> Axis {
let absolutePoint = CGPointMake(p2.x - p1.x, p2.y - p1.y)
let radians = atan2(Double(absolutePoint.x), Double(absolutePoint.y))
let absRad = fabs(radians)
if absRad > M_PI_4 && absRad < 3*M_PI_4 {
return .X
} else {
return .Y
}
}

Comparing two values and returning the greatest of the two

I have two CGPoints that are the locations of two corners of a frame's rectangle.
I need to give separate instructions to them — one set of instructions for the one on top (on a vertical plane), and another set for the bottom one.
How would I go about comparing them and then giving them separate instructions?
If you have two CGPoints, if one is above the other, then it has a lower y value than the other.
For example: take two points:
CGPoint point1 = CGPointMake(100.0, 120.0);
CGPoint point2 = CGPointMake(100.0, 80.0);
You could write a method:
- (NSComparisonResult)compareYValueOfPoint:(CGPoint)point1 toPoint:(CGPoint)point2
{
CGFloat y1 = point1.y;
CGFloat y2 = point2.y;
if (y1 == y2) {
return NSOrderedSame;
} else if (y1 < y2) {
return NSOrderedAscending;
} else {
return NSOrderedDescending;
}
}
and call it with:
NSComparisonResult result = [self compareYValueOfPoint:point1 toPoint:point2];
And depending on the result, use the relevant point for further actions.
A CGPoint is a composite value (struct) containing two fields, x & y.
If you have two arbitrary points then one is "above" the other if its y-coordinate is greater than the other's y-coord. One is to the right of the other if its x-coordinate is greater.
CPPoint one, two;
if (one.y > two.y) { // one is above two }
if (two.x > one.x) { // two is to the right of one }
use ternary operators to initialise new variables into a known order...
CGPoint upperPoint = ((one.y < two.y) ? one : two);
CGPoint lowerPoint = ((one.y < two.y) ? two : one);
or maybe use fMax / fMin type macros...
CGFloat lesserYvalue = ((CGFloat) fMinf(one.y , two.y) );
CGFloat greaterYvalue = ((CGFloat) fMaxf(one.y , two.y) );

Moving and rotating a sprite with Accelerometer in SpriteKit

I'm trying to make my first game using Spritekit, so i have a sprite that i need to move around using my accelerometer. Well, no problem doing that; movement are really smooth and responsive, the problem is that when i try to rotate my sprite in order to get it facing its own movement often i got it "shaking" like he has parkinson. (:D)
i did realize that this happens when accelerometer data are too close to 0 on one of x, y axes.
So the question: Is there a fix for my pet parkinson?? :D
Here is some code:
-(void) update:(NSTimeInterval)currentTime{
static CGPoint oldVelocity;
//static CGFloat oldAngle;
if(_lastUpdatedTime) {
_dt = currentTime - _lastUpdatedTime;
} else {
_dt = 0;
}
_lastUpdatedTime = currentTime;
CGFloat updatedAccelX = self.motionManager.accelerometerData.acceleration.y;
CGFloat updatedAccelY = -self.motionManager.accelerometerData.acceleration.x+sinf(M_PI/4.0);
CGFloat angle = vectorAngle(CGPointMake(updatedAccelX, updatedAccelY));
_velocity = cartesianFromPolarCoordinate(MAX_MOVE_PER_SEC, angle);
if(oldVelocity.x != _velocity.x || oldVelocity.y != _velocity.y){
_sprite.physicsBody.velocity = CGVectorMake(0, 0);
[_sprite.physicsBody applyImpulse:CGVectorMake(_velocity.x*_sprite.physicsBody.mass, _velocity.y*_sprite.physicsBody.mass)];
_sprite.zRotation = vectorAngle(_velocity);
oldVelocity = _velocity;
}
}
static inline CGFloat vectorAngle(CGPoint v){
return atan2f(v.y, v.x);
}
i did try to launch the update of the _velocity vector only when updatedAccelX or updatedAccelY are, in absolute value >= of some values, but the result was that i got the movement not smooth, when changing direction if the value is between 0.1 and 0.2, and the problem wasn't disappearing when the value was under 0.1.
i would like to maintain direction responsive, but i also would like to fix this "shake" of the sprite rotation.
I'm sorry for my bad english, and thanks in advance for any advice.
You can try a low pass filter (cf. to isolate effect of gravity) or high pass filter (to isolate effects of user acceleration).
#define filteringFactor 0.1
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
//low pass
accelerX = (acceleration.x * filteringFactor) + (accelerX * (1.0 - filteringFactor));
//idem … accelerY
//idem … accelerZ
//or high pass
accelerX = acceleration.x - ( (acceleration.x * filteringFactor) + (accelerX * (1.0 - filteringFactor)) );
//idem … accelerY
//idem … accelerZ
}

If with CGPointEqualToPoint do not work

Im trying to figure out why this function do not execute theGameEnd function, when ball position is exactly the same as block position and when anchorpoints are the same.
if (CGPointEqualToPoint(ball.position,block.position)) {
if (CGPointEqualToPoint(ball.anchorPoint,monster1.anchorPoint)) {
[self theGameEnd];
}
}
The implementation of CGPointEqualToPoint is
CG_INLINE bool __CGPointEqualToPoint(CGPoint point1, CGPoint point2)
{
return point1.x == point2.x && point1.y == point2.y;
}
... so coordinates have to be absolutely equal to return true.
This is not always the case with CGFloat types, even if pixels seem to be aligned. There might be tiny errors resulting from the way you calculate them in your animation or game simulation code.
You could try to round the values before comparing them or allow for a small deviation.

How do you move an IOS SKSprite at a consistent speed

Playing around with SKSprites in the IOS SpriteKit, and I basically want to have a sprite randomly move a certain direction for a certain distance, then pick a new random direction and distance.. Simple enough, create a method that generates the random numbers then creates the animation and in the completion block of the animation have it callback the same routine.
THis does work, but it also keeps the animation from moving at the same velocity since the animations are all based on duration.. If the object has to move 100 it moves at 1/2 the speed it moves if the next random tells it to move 200... So how the heck do I have it move with a consistent speed?
#Noah Witherspoon is correct above - use Pythagorus to get a smooth speed:
//the node you want to move
SKNode *node = [self childNodeWithName:#"spaceShipNode"];
//get the distance between the destination position and the node's position
double distance = sqrt(pow((destination.x - node.position.x), 2.0) + pow((destination.y - node.position.y), 2.0));
//calculate your new duration based on the distance
float moveDuration = 0.001*distance;
//move the node
SKAction *move = [SKAction moveTo:CGPointMake(destination.x,destination.y) duration: moveDuration];
[node runAction: move];
Using Swift 2.x I've solved with this little method:
func getDuration(pointA:CGPoint,pointB:CGPoint,speed:CGFloat)->NSTimeInterval {
let xDist = (pointB.x - pointA.x)
let yDist = (pointB.y - pointA.y)
let distance = sqrt((xDist * xDist) + (yDist * yDist));
let duration : NSTimeInterval = NSTimeInterval(distance/speed)
return duration
}
With this method i can use an ivar myShipSpeed and directly call my actions for example :
let move = SKAction.moveTo(dest, duration: getDuration(self.myShip.position,pointB: dest,speed: myShipSpeed))
self.myShip.runAction(move,completion: {
// move action is ended
})
As an extension to #AndyOS's answer, if you're going to move only along one axis (X for example) you can simplify the math by doing this instead:
CGFloat distance = fabs(destination.x - node.position.x);

Resources