加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift 3(SpriteKit):锁定SKSpriteNode的x轴及其physicsBody

发布时间:2020-12-14 05:40:14 所属栏目:百科 来源:网络整理
导读:我真的需要知道如何锁定SKSpriteNode的x轴及其physicsBody.我需要保持SKSpriteNode动态和affectedByGravity.节点在斜坡上,因此这就是x轴因重力而移动的原因.但是,我不希望此SKSpriteNode的x轴因重力而移动.有没有办法锁定x轴以实现这一目标? 谢谢你的帮助:
我真的需要知道如何锁定SKSpriteNode的x轴及其physicsBody.我需要保持SKSpriteNode动态和affectedByGravity.节点在斜坡上,因此这就是x轴因重力而移动的原因.但是,我不希望此SKSpriteNode的x轴因重力而移动.有没有办法锁定x轴以实现这一目标?
谢谢你的帮助:D

编辑:我试图将约束应用于x值,如下所示:

let xConstraint = SKConstraint.positionX(SKRange(constantValue: 195))
node.constraints?.append(xConstraint)

然而,这不起作用,我不知道为什么以及如何解决它.有人知道解决方案吗?

编辑2:SKPhysicsJointPin实际上看起来更有前途.在对这个问题的第一个回答/回答的评论中,我一直试图想出如何在我的情况下正确使用它.

我的代码示例:

let node = SKSpriteNode(imageNamed: "node")

enum collisionType: UInt32 {
    case node = 1
    case ground = 2
    case other = 4 //the other node is unrelated to the ground and node
}

class GameScene: SKScene,SKPhysicsContactDelegate {

override func didMove(to view: SKView) {
    //Setup node physicsBody
    node.physicsBody = SKPhysicsBody(rectangleOf: node.size)
    node.physicsBody?.categoryBitMask = collisionType.node.rawValue
    node.physicsBody?.collisionBitMask = //[other node that isn't the ground or the node]
    node.physicsBody?.contactTestBitMask = //[other node that isn't the ground or the node]
    node.physicsBody?.isDynamic = true
    node.physicsBody?.affectedByGravity = true
    addChild(node)

    //Physics Setup
    physicsWorld.contactDelegate = self
}

节点位于地面之上,地面由各种SKSpriteNode线组成,这些线具有基于体积的physicsBody.地面不断在前面添加新线,并移除后面的线,并将每条线的x值更改为负值(因此地面似乎在移动 – 此过程在SKAction中执行).这些线(地面的部分)是一个角度,这就是节点的x轴移动的原因.我希望节点始终位于地面的前面(例如,始终位于新创建的线的顶部).目前,像这样设置节点的位置会锁定x轴(解决我的问题):

override func didSimulatePhysics() {
    //Manage node position
    node.position.x = 195
    node.position.y = CGFloat([yPosition of the first line of the ground - the yPosition keeps changing]) 
}

注意:^这个^函数在GameScene类中

x轴实际上保持不变.然而,问题是现在节点的physicsBody低于节点的中心(之前没有发生过).

默认情况下,节点的constraints属性为nil.您需要创建一个包含一个或多个约束的数组,并将其分配给属性.例如
let xConstraint = SKConstraint.positionX(SKRange(constantValue: 195))
node.constraints = [xConstraint]

更新

您可能希望使用摄像机节点而不是在场景中移动地面.使用摄像机节点,可以移动主角和摄像机而不是地面.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读