所以在我的应用程序中我使用下面的代码来反弹球,但问题是如果我向右按球,球会向左反弹,如果向左按,则向左反弹。如果我按在中间,它会像往常一样直线弹起。这是我正在使用的代码:
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()
}
}
答案 0 :(得分:1)
尝试添加此功能:
func vectorFrom(point pointA: CGPoint, to pointB: CGPoint) -> CGVector {
let vector = CGVector(dx: pointB.x - pointA.x, dy: 310.0)
return vector
}
然后改变这一行:
self.ball!.physicsBody?.applyImpulse(CGVector(dx: xpower, dy: self.jumpAmount))
到此:
let dirVector = vectorFrom(point: tpoint, to: ball!.position)
ball!.physicsBody?.applyImpulse(dirVector)
如果这对您没有用,请告诉我!
答案 1 :(得分:0)
尝试更改
if xpo > 0 {
xpower = xpower * -1
}
要
if xpo > 0 {
xpower = xpower * 1.5
}