Impulse SKSpriteNode depending on touched location Swift 2

℡╲_俬逩灬. 提交于 2019-12-09 01:57:25

问题


I'm learning Swift 2 and I'm making the typical ball game where you hit the ball, it gets an impulse. But i don't want the ball to always go straight through Y coordinate, it wouldn't be fun, i would like to add an impulse depending on the touched location, go through the opposite direction.

I attempted this example that ABakerSmith gave to the OP, but what it does is just spin my ball in the same place and baaarely moving it to one side.

So i got this code, already detecting the ball Sprite touch, working fine. Extended CGVector like he mentioned.

What am I doing wrong here? maybe the calculations on the extended CGVector are wrong for my case?

Also I have to consider that it shouldn't move down, only up and both directions left or right, but not down.

UPDATED This is the code:

        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)
      }

And this is the extended CGVector code:

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
    }
}

来源:https://stackoverflow.com/questions/37998343/impulse-skspritenode-depending-on-touched-location-swift-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!