快速移动并通过触摸释放物体

时间:2014-07-15 12:51:12

标签: swift

我是编码的新手。我用快速精灵套件创建了一个带有球和地板的场景。执行时,球会在地板上掉落并反弹。我正在寻找一些关于如何移动和投球的建议。

2 个答案:

答案 0 :(得分:3)

要检测拖球,您必须创建UIPanGestureRecognizer并将其添加到球的视图中

let dragBall = UIPanGestureRecognizer(target: self, action:"dragBall:") ball.addGestureRecognizer(dragBall)

下一步是实现“dragBall”功能,它将处理拖动事件,例如:

@IBAction func dragBall(recognizer: UIPanGestureRecognizer) {
  let point = recognizer.locationInView(self.view);
  ball.center.x=point.x
  ball.center.y=point.y
}

您还应该为拖动时间禁用此对象的重力,您可以通过检查手势识别器的状态来检查Pan手势是否结束,如果状态为UIGestureRecognizerStateEnded,则应再次添加重力

答案 1 :(得分:0)

import SpriteKit

class GameScene: SKScene {
    let ball = SKSpriteNode(imageNamed: "ball")

    override func didMoveToView(view: SKView) {
        /* Setup your scene here */
        ball.position = CGPoint(x:500,y:500)
        ball.anchorPoint = CGPoint(x:0.0,y:0.0)
        ball.size = CGSize(width: 60, height: 60)

        // physics
        ball.physicsBody = SKPhysicsBody(circleOfRadius: 1)
        // this defines the mass, roughness and bounciness
        ball.physicsBody.friction = 0.2
        ball.physicsBody.restitution = 0.8
        ball.physicsBody.mass = 0.1
        // this will allow the balls to rotate when bouncing off each other
        ball.physicsBody.allowsRotation = true
        self.addChild(ball)
    }

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

    }

    override func touchesMoved(touches: NSSet, withEvent event: UIEvent)
    { ball.position = touches.anyObject().locationInNode(self); }


    override func update(currentTime: CFTimeInterval) {
        /* Called before each frame is rendered */
    }
}

到了那天结束时,我制定了一些代码,但似乎很难保持球状