我正在使用下面的代码绘制从触摸到触摸释放的四边形曲线,并在这些触摸点之间添加一个球作为曲线的控制点。如何让用户拖动此球并依次调整四边形曲线的尺寸?
下面的代码描绘了从触摸点到触摸释放的一条线,我尝试将它与允许拖动对象的代码相结合,但我需要将拖动连接到实际移动控制点,然后修改原始曲线。
导入SpriteKit 导入GameKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var movableNode : SKNode?
let controlBall = SKShapeNode(circleOfRadius: 10)
let myPath = CGMutablePath()
struct PhysicsCategory {
static let lineCategory : UInt32 = 4
}
var startPoint : CGPoint = CGPoint.zero
var endPoint : CGPoint = CGPoint.zero
var controlPoint : CGPoint = CGPoint.zero
override func didMove(to view: SKView) {
self.physicsBody = SKPhysicsBody(edgeLoopFrom: self.frame)
self.physicsBody?.categoryBitMask = PhysicsCategory.lineCategory
controlBall.zPosition = +1
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
if controlBall.contains(location) {
movableNode = controlBall
movableNode?.position = location
} else {
startPoint = touch.location(in: self)
myPath.move(to: touch.location(in: self))
}
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first, movableNode != nil {
movableNode?.position = touch.location(in: self)
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
if let touch = touches.first, movableNode != nil {
movableNode?.position = touch.location(in: self)
movableNode = nil
}
endPoint = touch.location(in: self)
var controlPoint = CGPoint(x:(startPoint.x-(startPoint.x - endPoint.x)/2), y: startPoint.y - ((startPoint.y - endPoint.y)/2))
myPath.addQuadCurve(to: endPoint, control: controlPoint)
let controlBall = SKShapeNode(circleOfRadius: 10)
controlBall.fillColor = SKColor.red
controlBall.strokeColor = SKColor.black
controlBall.position = CGPoint(x:controlPoint.x, y: controlPoint.y)
self.addChild(controlBall)
let line = SKShapeNode(path: myPath)
line.lineWidth = 5.0
line.strokeColor = SKColor.blue
line.physicsBody = SKPhysicsBody(edgeLoopFrom: myPath)
line.physicsBody?.categoryBitMask = PhysicsCategory.lineCategory
self.addChild(line)
line.physicsBody = SKPhysicsBody(edgeFrom: startPoint, to: endPoint)
}
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
movableNode = nil
}
}
}