Impulse SKSpriteNode取决于触摸位置Swift 2

时间:2016-06-23 17:37:01

标签: ios swift sprite-kit

我正在学习Swift 2,而且我正在制作典型的球类比赛,你会有一个冲动。但是我不希望球总是直接穿过Y坐标,这不会很有趣,我想根据触摸位置添加一个冲动,然后反方向。

我尝试了ABakerSmith给OP的这个example,但是它的作用只是将我的球旋转到同一个地方,然后将它移到一边。

所以我得到了这个代码,已经检测到Sprite触控球,工作正常。像他提到的扩展的CGVector。

我在这里做错了什么?也许扩展的CGVector上的计算对我来说是错误的?

此外,我必须考虑它不应向下移动,只向上和向左或向右移动,但不能向下移动。

更新这是代码:

        ball = SKSpriteNode(imageNamed: "ball")
        ball.name = ballCategoryName
        ball.userInteractionEnabled = false
        ball.setScale(0.3)
        ball.zPosition = 2
        ball.position = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2)
        ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.width / 2)
        ball.physicsBody?.friction = 0
        ball.physicsBody?.restitution = 0.7
        ball.physicsBody?.linearDamping = 0
        ball.physicsBody?.allowsRotation = true
        ball.physicsBody?.categoryBitMask = PhysicsCategory.ball
        ball.physicsBody?.dynamic = true
        ball.physicsBody?.affectedByGravity = false

        self.addChild(ball)

        /* during touchesBegan func() */
        if node.name == "ball" {
                score += 1
                scoreLabel.text = "\(score)"

                ball.physicsBody?.velocity = CGVectorMake(0, 0);
                let ballCenter = CGVectorMake(ball.position.x + ball.frame.width / 2,
                                              ball.position.y + ball.frame.height / 2)

                let reflectedPoint = CGVectorMake(2 * ballCenter.dx - location.x,
                                                  2 * ballCenter.dy - location.y)

                print(location.x, location.y, " vs ", reflectedPoint.dx, reflectedPoint.dy)

                ball.physicsBody?.applyImpulse(reflectedPoint, atPoint: location)
      }

这是扩展的CGVector代码:

import Foundation
import SpriteKit

extension CGVector {
    init(p1: CGPoint, p2: CGPoint) {
        self.dx = p1.x - p2.x
        self.dy = p1.y - p2.y
    }

    var length: CGFloat {
        get { return hypot(dx, dy) }

        set {
            normalise()
            dx *= newValue
            dy *= newValue
        }
    }

    mutating func normalise() {
        dx /= length
        dy /= length
    }
}

0 个答案:

没有答案