In meiner Anwendung verwende ich den unten stehenden Code, um den Ball zu prellen, aber das Problem ist, dass der Ball nach links springt, wenn ich rechts drücke, und links, wenn ich nach links drücke. Wenn ich in der Mitte drücke, springt es wie gewohnt senkrecht nach oben. Dies ist der Code Ich verwende:Swift SpriteKit touchesBegan detect right/left
var PlayingFlag:Bool = false
let jumpAmount:Double = 310.0
var Ballx1:CGFloat = 0.0
var Ballx2:CGFloat = 0.0
var Ballx3:CGFloat = 0.0
var Ballx4:CGFloat = 0.0
var BallMoveAmount = (10.0, 100.0, 150.0, 200.0)
func CreateBall(){
let ballTexture = SKTexture(imageNamed: "ball")
ballTexture.filteringMode = .Nearest
self.ball = SKSpriteNode(texture: ballTexture)
self.ball!.physicsBody = SKPhysicsBody(texture: ballTexture, size: ball!.size)
self.ball!.physicsBody?.dynamic = true
self.ball!.physicsBody?.allowsRotation = true
self.ball!.physicsBody?.restitution = 0.6
self.ball!.physicsBody?.mass = 0.430 // m = 430g
self.ball!.position = CGPoint(x: self.frame.size.width/2 , y: self.frame.size.height)
self.ball!.physicsBody?.collisionBitMask = 0x1 << 1
self.ball!.zPosition = 10
self.addChild(self.ball!)
let Ballx0 = ball!.size.width
self.Ballx1 = Ballx0 * 0.2
self.Ballx2 = Ballx0 * 0.4
self.Ballx3 = Ballx0 * 0.6
self.Ballx4 = Ballx0 * 0.8
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let ballHeight = self.ball!.size.height
for touch : UITouch in touches{
let tpoint = touch.locationInNode(self)
if tpoint.y < (self.ball!.position.y + (ballHeight/2.0)) {
if tpoint.y > (self.ball!.position.y - (ballHeight/2.0))
{
var xpower:Double = 0.0
let xpo = abs(tpoint.x - self.ball!.position.x)
if(xpo < self.Ballx1){
xpower = BallMoveAmount.0
}else if (xpo < self.Ballx2) {
xpower = BallMoveAmount.1
}else if (xpo < self.Ballx3) {
xpower = BallMoveAmount.2
}else if (xpo < self.Ballx4) {
xpower = BallMoveAmount.3
}else{
return
}
if xpo > 0 {
xpower = xpower * -1
}
self.ball!.physicsBody?.velocity = CGVector.zero
self.ball!.physicsBody?.applyImpulse(CGVector(dx: xpower, dy: self.jumpAmount))
self.ball!.runAction(se_ball)
if !self.PlayingFlag { // initial touch
self.gonode?.removeFromParent()
self.PlayingFlag = true
}else{
//something else
}
}
}
}
}
func didBeginContact(contact: SKPhysicsContact) {
if !self.PlayingFlag { return }
if contact.bodyA.node == self.floorSprite || contact.bodyB.node == self.floorSprite {
self.PlayingFlag = false
// Game over...
self.ball?.removeFromParent()
}
}
Funktioniert perfekt. -Danke! –