【发布时间】:2019-06-27 18:36:52
【问题描述】:
我有一个 SKSpriteNode,我在其中设置了 centerRect 属性,以便可以拉伸节点以使其看起来像一条样式线。我的意图是让用户触摸屏幕,并用节点绘制/拖动一条直线。这条线将围绕一个锚点旋转以保持笔直。
在touchesBegan:中,添加了节点:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let positionInScene = touch.location(in: self)
if let _ = fgNode.childNode(withName: "laser") {
print("already there")
} else {
laser.centerRect = CGRect(x: 0.42857143, y: 0.57142857, width: 0.14285714, height: 0.14285714)
laser.anchorPoint = CGPoint(x: 0, y: 0.5)
laser.position = positionInScene
fgNode.addChild(laser)
}
}
并在touchesMoved:中调整:
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let positionInScene = touch.location(in: self)
stretchLaserTo(positionInScene)
}
节点的拉伸和旋转有两个功能:
func stretchLaserTo(_ point: CGPoint) {
let offset = point - laser.anchorPoint
let length = offset.length()
let direction = offset / CGFloat(length)
laser.xScale = length
rotate(sprite: laser, direction: direction)
}
func rotate(sprite: SKSpriteNode, direction: CGPoint) {
sprite.zRotation = atan2(direction.y, direction.x)
}
我认为我在某种程度上是在正确的轨道上。这条线随着我的触摸而旋转并扩展,但是,它非常敏感,不会随着我的触摸而停留。也许我做错了。是否有执行此类操作的标准技术?
可以在此处查看此工作的示例:https://imgur.com/A83L45i
【问题讨论】:
标签: ios swift iphone sprite-kit