(Swift SpriteKit)沿触摸方向旋转精灵 [英] (Swift SpriteKit) Rotate sprite in the direction of touch

查看:85
本文介绍了(Swift SpriteKit)沿触摸方向旋转精灵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在提供的屏幕截图中,红色箭头和叉号仅用于演示目的,不在游戏中.我希望太空飞船的精灵面对射出的球的方向.

On the screenshot provided, the red arrow and cross are just for demonstration purposes and are not in the game. I would like the sprite of the spaceship to face the direction of the ball it shoots.

链接到图像

这是我当前的触摸位置代码

Here is my current code for touch location

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
   /* Called when a touch begins */

    for touch in touches {
        let location = touch.locationInNode(self)

        var bullet = SKSpriteNode(imageNamed: "bullet")
        bullet.position = cannon.position
        bullet.size = CGSize(width: 35, height: 35)

        //physics
        bullet.physicsBody = SKPhysicsBody(circleOfRadius: bullet.size.width/2)
        bullet.physicsBody?.categoryBitMask = PhysicsCategory.bullet
        bullet.physicsBody?.collisionBitMask = PhysicsCategory.enemy
        bullet.physicsBody?.contactTestBitMask = PhysicsCategory.enemy
        bullet.name = "bullet"
        bullet.physicsBody?.affectedByGravity = false

        self.addChild(bullet)

        var dx = CGFloat(location.x - cannon.position.x)
        var dy = CGFloat(location.y - cannon.position.y)

        let magnitude = sqrt(dx * dx + dy * dy)

        dx /= magnitude
        dy /= magnitude

        let vector = CGVector(dx: 120.0 * dx, dy: 120.0 * dy) //adjust constant to increase impluse.

        bullet.physicsBody?.applyImpulse(vector)

        // I found this code bellow this comment, but it just moves the cannon's y position

        let direction = SKAction.moveTo(
            CGPointMake(
                400 * -cos(bullet.zRotation - CGFloat(M_PI_2)) + bullet.position.x,
                400 * -sin(bullet.zRotation - CGFloat(M_PI_2)) + bullet.position.y
            ),
            duration: 0.8)

        cannon.runAction(direction)
    }
}

推荐答案

这是我发现的完美运行的代码.

Here is the code I found which works perfectly.

旋转使用Swift的SpriteKit中的sprite到sprite位置不完全

 let angle = atan2(location.y - cannon.position.y , location.x - cannon.position.x)
 cannon.zRotation = angle - CGFloat(M_PI_2)

这篇关于(Swift SpriteKit)沿触摸方向旋转精灵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆