【问题标题】:How to calculate the "center" point of a curved SKSpriteNode?如何计算弯曲 SKSpriteNode 的“中心”点?
【发布时间】:2017-10-17 07:06:23
【问题描述】:

我正在通过 SKShapeNode 的纹理初始化和显示 SKSpriteNode,该纹理具有表示圆的一部分的特定路径。下面是我使用游乐场生成的形状示例:

import SpriteKit
import PlaygroundSupport

let view = SKView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
let scene = SKScene(size: view.frame.size)
view.presentScene(scene)

let radius: CGFloat = view.frame.width * 0.40

var length: CGFloat = (.pi * 2.0) / 8.0
var width: CGFloat  = radius / 5.0

var path: CGPath {

    let path = UIBezierPath(arcCenter: view.center, radius: radius, startAngle: 0.0, endAngle: length, clockwise: true)
    path.addArc(withCenter: view.center, radius: radius - width, startAngle: length, endAngle: 0.0, clockwise: false)

    path.close()

    return path.cgPath
}

let shapeNode = SKShapeNode(path: path)
shapeNode.fillColor = .white
let texture = view.texture(from: shapeNode)!

let spriteNode = SKSpriteNode(texture: texture, color: .white, size: texture.size())
spriteNode.position = CGPoint(x: shapeNode.frame.midX, y: shapeNode.frame.midY)

scene.addChild(spriteNode)

PlaygroundPage.current.liveView = view

这会生成这个形状:

我想添加一个小子 SKSpriteNode,它以弯曲节点的宽度为中心并位于中间弧点,如下所示:

我最接近的是使用 spriteNode 的位置:

let childNode = SKSpriteNode(color: .red, size: CGSize(width: 5, height: 5))
childNode.position = spriteNode.position
scene.addChild(childNode)

这会产生一些接近的东西,但它正在使用框架,这是完全错误的:

我假设我需要对弧的路径做一些事情,但我不确定如何做。有人能指出我正确的方向吗?

【问题讨论】:

  • 从 SKShapeNode 计算它是有问题的,因为路径可以任意复杂。 – 但是您知道距中心的距离和角度。剩下的是基本的三角函数:)
  • 有时听到答案很容易掌握就是人们需要听到的全部内容。谢谢!

标签: ios swift sprite-kit uibezierpath skspritenode


【解决方案1】:

感谢 cmets 我避免使用路径并刷新了一些基本的触发来解决:

let x = (radius - width/2) * cos(length/2) + view.center.x
let y = (radius - width/2) * sin(length/2) + view.center.y
childNode.position = CGPoint(x: x, y: y)

【讨论】:

    猜你喜欢
    • 2016-07-30
    • 2015-01-11
    • 2015-01-10
    • 1970-01-01
    • 2018-01-19
    • 2014-03-09
    • 2016-06-02
    • 2013-09-16
    • 1970-01-01
    相关资源
    最近更新 更多