ios - SKNode 在 SKConstraint 范围内跟随另一个 SKNode

标签 ios swift sprite-kit

我正在尝试使用 SpriteKit 模拟一只眼睛。

当用户的手指在屏幕上移动时,眼睛的瞳孔会跟踪用户的手指,但必须保持在眼睛的范围内。

我曾尝试使用 SKConstraint 解决此问题,但未成功。

编辑

我的想法是对瞳孔应用 SKConstraints 以限制其边界到眼睛。任何触摸(即 touchesMoved() 等)都将以 SKAction.moveTo() 的形式应用于瞳孔,并且 SpriteKit 会处理将瞳孔保持在眼睛范围内。

let touchPoint = CGPoint()
SKAction.moveTo( touchPoint, duration: 2)

视频代码可用:https://gist.github.com/anonymous/f2356e07d1ac0e67c25b1940662d72cb

Eyeball video demo

一图胜千言...

想象一下,瞳孔是一个白色的小圆圈。蓝色框模拟用户在屏幕上移动手指。

理想情况下,瞳孔会跟随屏幕周围的蓝色框并遵循黄色圆圈定义的路径。

iOS 10 | swift 3 | Xcode 8

最佳答案

您可以使用方向约束来旋转节点以面向触摸位置,而不是通过距离进行约束。通过将具有 x 偏移量的“瞳孔”节点添加到受约束的节点,瞳孔将移向触摸点。以下是如何执行此操作的示例:

let follow = SKSpriteNode(color:.blue, size:CGSize(width:10,height:10))
let pupil = SKShapeNode(circleOfRadius: 10)
let container = SKNode()
let maxDistance:CGFloat = 25

override func didMove(to view: SKView) {
    addChild(container)
    // Add the pupil at an offset
    pupil.position = CGPoint(x: maxDistance, y: 0)
    container.addChild(pupil)

    // Node that shows the touch point
    addChild(follow)

    // Add an orientation constraint to the container
    let range = SKRange(constantValue: 0)        
    let constraint = SKConstraint.orient(to: follow, offset: range)
    container.constraints = [constraint]
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for t in touches {
        let location = t.location(in: self)
        follow.position = location
        adjustPupil(location: location)
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    for t in touches {
        let location = t.location(in: self)
        follow.position = location
        adjustPupil(location: location)
    }
 }

// Adjust the position of the pupil within the iris
func adjustPupil(location:CGPoint) {
    let dx = location.x - container.position.x
    let dy = location.y - container.position.y
    let distance = sqrt(dx*dx + dy*dy)
    let x = min(distance, maxDistance)
    pupil.position = CGPoint(x:x, y:0)
}

enter image description here

关于ios - SKNode 在 SKConstraint 范围内跟随另一个 SKNode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40850937/

相关文章:

ios - CoreData : Opening a standalone . xcdatamodeld 文件和更改当前模型版本

IOS -webkit-overflow-scrolling 在错误的轴上滚动,或者根本不滚动

ios - GMSPanoramaView 黑屏

ios - 如何修复使用前置摄像头镜像、AVFoundation、Swift 捕获图像

arrays - 将字符串数组中名称的第一个字符提取到另一个数组中

ios - 加速计在第一款游戏中有效,但在第二款游戏中变得疯狂

ios - Swift:检查用户输入计数以继续

Swift:在循环中检查对象类型

ios - 根据屏幕大小更改节点定位 Swift/Sprite Kit

swift - SpriteKit 没有释放所有使用的内存