Search code examples
iosvectorsprite-kitgame-physicsskphysicsbody

Keeping Direction of a Vector Constant while Rotating Sprite


I'm trying to make a game where the sprite will always move to the right when hit by an object. However since the Sprite rotates constantly and the zero radians rotates with the Sprite causes my calculated magnitude to go the opposite direction if the sprite is facing left and hits the object. Is there a way to keep the direction of the magnitude always pointing to the right even if the zero is facing left?

        // referencePoint = upper right corner of the frame 
        let rightTriangleFinalPoint:CGPoint = CGPoint(x: referencePoint.x, y: theSprite.position.y)

        let theSpriteToReferenceDistance = distanceBetweenCGPoints(theSprite.position, b: referencePoint)
        let theSpriteToFinalPointDistance = distanceBetweenCGPoints(theSprite.position, b: rightTriangleFinalPoint)
        let arcCosineValue = theSpriteToFinalPointDistance / theSpriteToReferenceDistance
        let angle = Double(acos(arcCosineValue))

        let xMagnitude = magnitude * cos(angle)
        let yMagnitude = (magnitude * sin(angle)) / 1.5

Solution

  • So I figured out what was going on.

    It seems like the angle doesn't rotate with the Sprite like I originally thought and the vector that I am making is working with the code above. THE problem that I had was that I also set the collision bit for the objects which is wrong. If I only set the contact bit for the objects against the sprite the my desired outcome comes true.