IOS Sprite Kit, how to make a point with an aim on the target in landscape orientation?

I have an icon in my game with a set of sprites, which I intend to use as an animated projectile when one character shoots another. I am trying to orient this projectile to indicate a target.

enter image description here

I rotate it at the base angle pi / 4.0 to direct it right to the right. then I want the arrow to turn from this position and point to the target.

The code below almost works, but, in my opinion, it always looks as if the projectile is turned off at the right angle. If the angle is correct, the arrow will indicate the direction of movement when the arrow is given an action to go to the x, y coordinate.

How to correctly calculate the angle of fire from one (x, y) point to another (x, y) point?

EDIT: the code below works, just need to do zeroCheckedY / zeroCheckedX.

//correct for pointing in the bottom right corner    
    float baseRotation = M_PI/4.0;   
    float zeroCheckedY = destination.y - origin.y;
    float zeroCheckedX = destination.x - origin.x;
    SKAction* rotate = nil;
    if(zeroCheckedX != 0)
    {
//not sure if I'm calculating this angle correctly.
        float angle =  atanf(zeroCheckedY/zeroCheckedX);
        rotate =  [SKAction rotateByAngle:baseRotation + angle duration:0];
    }else
    {
        rotate =  [SKAction rotateByAngle:baseRotation duration:0];

    }
+4
source share
1 answer

I had a similar problem: the gun should "track" the target. In CannonNodeI defined the following method:

- (void)catchTargetAtPoint:(CGPoint)target {
    CGPoint cannonPointOnScene = [self.scene convertPoint:self.position fromNode:self.parent];
    float angle = [CannonNode pointPairToBearingDegreesWithStartingPoint:cannonPointInScene endingPoint:target];
    if (self.zRotation < 0) {
        self.zRotation = self.zRotation + M_PI * 2;
    }
    if ((angle < self.maxAngle) && (angle> self.minAngle)) {
        [self runAction:[SKAction rotateToAngle:angle duration:1.0f]];
    }
}

+ (float)pointPairToBearingDegreesWithStartingPoint:(CGPoint)startingPoint endingPoint:(CGPoint) endingPoint {
    CGPoint originPoint = CGPointMake(endingPoint.x - startingPoint.x, endingPoint.y - startingPoint.y); // get origin point to origin by subtracting end from start
    float bearingRadians = atan2f(originPoint.y, originPoint.x); // get bearing in radians
    return bearingRadians;
}

catchTargetAtPointmust be called inside the updatescene method .

+3
source

All Articles