Rotate a sprite to sprite position not exact in SpriteKit with Swift

后端 未结 3 423
既然无缘
既然无缘 2021-01-13 02:33

I\'m trying to rotate a player to the touch. Using the touches move function, I set the location to a variable. I then call a function. It works but the angle is off. Locati

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-13 03:01

    Use an orientation constraint to rotate your object to the touch position:

    // Create two global Sprite properties:
    
    var heroSprite = SKSpriteNode(imageNamed:"Spaceship")
    var invisibleControllerSprite = SKSpriteNode()
    
    override func didMoveToView(view: SKView) {         
    
       // Create the hero sprite and place it in the middle of the screen
       heroSprite.xScale = 0.15
       heroSprite.yScale = 0.15
       heroSprite.position = CGPointMake(self.frame.width/2, self.frame.height/2)
       self.addChild(heroSprite)
    
       // Define invisible sprite for rotating and steering behavior without trigonometry
       invisibleControllerSprite.size = CGSizeMake(0, 0)
       self.addChild(invisibleControllerSprite)
    
       // Define a constraint for the orientation behavior
       let rangeForOrientation = SKRange(constantValue: CGFloat(M_2_PI*7))
    
       heroSprite.constraints = [SKConstraint.orientToNode(invisibleControllerSprite, offset: rangeForOrientation)]
    
    }
    
    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        /* Called when a touch begins */        
        for touch: AnyObject in touches {
    
            // Determine the new position for the invisible sprite:
            // The calculation is needed to ensure the positions of both sprites 
            // are nearly the same, but different. Otherwise the hero sprite rotates
            // back to it's original orientation after reaching the location of 
            // the invisible sprite
            var xOffset:CGFloat = 1.0
            var yOffset:CGFloat = 1.0
            var location = touch.locationInNode(self)
            if location.x>heroSprite.position.x {
                xOffset = -1.0
            }
            if location.y>heroSprite.position.y {
                yOffset = -1.0
            }
    
            // Create an action to move the invisibleControllerSprite. 
            // This will cause automatic orientation changes for the hero sprite
            let actionMoveInvisibleNode = SKAction.moveTo(CGPointMake(location.x - xOffset, location.y - yOffset), duration: 0.2)
            invisibleControllerSprite.runAction(actionMoveInvisibleNode)
    
            // Optional: Create an action to move the hero sprite to the touch location
            let actionMove = SKAction.moveTo(location, duration: 1)
            heroSprite.runAction(actionMove)
    
        }
    
    }
    

    Tutorial: http://stefansdevplayground.blogspot.de/2014/11/how-to-implement-space-shooter-with.html

    Video: https://youtu.be/8d8MH_gXt84

提交回复
热议问题