如何使物理体粘在节点锚点上 [英] How to make physics bodies stick to nodes anchor points

查看:17
本文介绍了如何使物理体粘在节点锚点上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的场景中间有四个正方形,分别设置了不同的锚点.轻按时,它们会一起移动并根据位置分开:

I have four squares in the middle of my scene set up with various anchor points. When tapped, they move together and come apart depending on what position:

 func rotate(angle : CGFloat, animated : Bool) {
    var rotateAction : SKAction!

    if animated {
        rotateAction = SKAction.rotateByAngle(angle, duration: 0.6)
    }
    else {
        rotateAction = SKAction.rotateByAngle(angle, duration: 0)
    }
    for node in self.children as! [SKSpriteNode] {

        node.runAction(rotateAction)
    }
}

}

我遇到的问题是节点的物理实体严格停留在锚点上,而不是节点本身,这给我带来了一堆问题.我怎样才能做到这一点,以便我可以为每个节点拥有我想要的锚点并使物理体直接留在节点上?如有必要,将发布更多代码.

The problem I have is that that the physics bodies of the nodes are strictly staying on the anchor points and not the nodes themselves which is giving me a mess of problems. How can I make it so that I can have the anchor point that I want for each node and make the physics bodies directly stay on the nodes? Will post more code if necessary.

推荐答案

你需要将锚点应用到物理体上,它不知道什么是精灵,它只是精灵使用的另一条信息,所以使用下面的计算来确定精灵的中心应该在哪里,并将其应用于物理体,以便它可以移动:

You need to apply the anchor point to the physics body, it has no understanding of what sprite is, it is just another piece of information sprite uses, so use the following calculation to determine where the center of the sprite should be, and apply that to the physics body so that it may shift:

 let centerPoint = CGPointMake(sprite.size.width / 2 - (sprite.size.width * sprite.anchorPoint.x), sprite.size.height / 2 - (sprite.size.height * sprite.anchorPoint.y))
 sprite.physicsBody = SKPhysicsBody(rectangleOfSize: sprite.size, center: centerPoint)

斯威夫特 3+:

 let centerPoint = CGPoint(x:sprite.size.width / 2 - (sprite.size.width * sprite.anchorPoint.x), y:sprite.size.height / 2 - (sprite.size.height * sprite.anchorPoint.y))
 sprite.physicsBody = SKPhysicsBody(rectangleOf: sprite.size, center: centerPoint)

更少的文字:

 let centerPoint = CGPoint(x:sprite.size.width * (0.5 - sprite.anchorPoint.x), y:sprite.size.height *(0.5 - sprite.anchorPoint.y))

这篇关于如何使物理体粘在节点锚点上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆