微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

swift – 如何在两条锚点之间保持30˚的距离

我正在尝试创建两条锚定在某个点(精灵)并旋转以在它们之间形成30度角的线.下面是我想要实现的图像.

enter image description here

这是我到目前为止所做的:

extension Int {
  var degreesToradians: Double { return Double(self) * .pi / 180 }
}
extension FloatingPoint {
  var degreesToradians: Self { return self * .pi / 180 }
  var radiansTodegrees: Self { return self * 180 / .pi }
}

class GameScene: SKScene,SKPhysicsContactDelegate {

var anchorSprite = SKSpriteNode(imageNamed: "anchorSprite")
var armleft = SKSpriteNode(imageNamed: "linesprite")
var armRight = SKSpriteNode(imageNamed: "linesprite")

override func didMove(to view: SKView) {

    self.physicsWorld.gravity = CGVector(dx: 0,dy: -1.8)
    self.physicsWorld.contactDelegate = self

    var tealBg = SKSpriteNode(imageNamed: "tealBg")
    tealBg.position = CGPoint(x: frame.midX,y: frame.midY)
    tealBg.zPosition = 10
    addChild(tealBg)

    anchorSprite.position = CGPoint(x: frame.midX,y: frame.midY + frame.midY/2)
    anchorSprite.zPosition = 20

    anchorSprite.physicsBody = SKPhysicsBody(rectangleOf: anchorSprite.frame.size)
    anchorSprite.physicsBody?.categoryBitMask = pinCategory
    anchorSprite.physicsBody?.isDynamic = false

    addChild(anchorSprite)

    armRight.anchorPoint = CGPoint(x: 0.5,y: 1)
    armRight.position = anchorSprite.position
    armRight.zPosition = 20
    armRight.physicsBody = SKPhysicsBody(rectangleOf: armRight.frame.size)
    armRight.zRotation = CGFloat(Double(15).degreesToradians)//CGFloat(Double.pi/6)
    armRight.physicsBody!.isDynamic = true
    addChild(armRight)

    armleft.anchorPoint = CGPoint(x: 0.5,y: 1)
    armleft.position = anchorSprite.position
    armleft.zPosition = 20
    armleft.physicsBody = SKPhysicsBody(rectangleOf: armRight.frame.size)
    armleft.zRotation = CGFloat(Double(-15).degreesToradians)//CGFloat(-Double.pi/6)
    armleft.physicsBody!.isDynamic = true
    addChild(armleft)

    //Pin joints
    var pinAndRightArmJoint = SKPhysicsJointPin.joint(withBodyA: anchorSprite.physicsBody!,bodyB: armRight.physicsBody!,anchor: CGPoint(x: anchorSprite.position.x,y: self.armRight.frame.maxY))
    self.physicsWorld.add(pinAndRightArmJoint)

    var pinAndLeftArmJoint = SKPhysicsJointPin.joint(withBodyA: anchorSprite.physicsBody!,bodyB: armleft.physicsBody!,y: self.armleft.frame.maxY))
    self.physicsWorld.add(pinAndLeftArmJoint)

}

下面是运行上面代码的图像(它们靠得很近).

enter image description here

如何确保线条总是相隔30˚并且即使在旋转时也能保持30˚的距离?

解决方法

为了让你的两条线分开正好30°,你可以使用一个SKPhysicsJointFixed,这听起来就是这样:它将两个物理实体固定在一个固定的位置.既然您已经按照自己想要的方式定位它们,只需将此代码添加到您拥有其他SKPhysicsJoints的位置即可:

let fixArms = SKPhysicsJointFixed.joint(withBodyA: armleft.physicsBody!,anchor: CGPoint.zero)
self.physicsWorld.add(fixArms)

结果:

Result image

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐