问题
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