使用Swift / SpriteKit的.applyImpulse角色不会跳

时间:2018-07-03 22:07:31

标签: swift xcode sprite-kit

问题:我的播放器不跳。它似乎对.applyImpulse没有响应,我在播放器的物理主体上调用它。如何使它跳跃?

这是我的第一场比赛,所以我不确定问题的根源在哪里。我已经在下面解释了相关的位。

在GameplayScene类中...

  • 我设置了createPlayer()中使用的播放器变量

    var player = Player();
    
  • 调用createPlayer()作为初始化函数的一部分

    func createPlayer() {
      player = Player(imageNamed: "testPlayer");
      player.initialize();
      player.position = CGPoint(x: -580, y: 200);
    
      self.addChild(player);
    }
    
  • 覆盖开始触摸功能

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
      print("in touchesBegan");
      player.jump();
    }
    

在Player类中...

  • 通过初始化函数中调用的辅助函数为播放器设置物理主体

    func setPhysics() {
      self.physicsBody = SKPhysicsBody(texture: self.texture!, size: self.texture!.size());
      self.setScale(0.25);
    
      self.physicsBody?.usesPreciseCollisionDetection = true;
      self.physicsBody?.categoryBitMask = PhysicsCategory.Player;
      self.physicsBody?.affectedByGravity = true;
      self.physicsBody?.allowsRotation = false;
    
      self.physicsBody?.collisionBitMask = PhysicsCategory.Ground;
      self.physicsBody?.contactTestBitMask = PhysicsCategory.Ground;
    }
    
  • 定义跳转功能

    func jump() {
      print("in jump function");
    
      let jumping = jumpPrep();
      self.run(jumping, withKey: "jumpKey");
    
      self.physicsBody?.velocity = CGVector(dx: 0, dy: 0);
      self.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 200));
    }
    
  • 我创建了在跳转功能中调用的动画

    func jumpPrep() -> SKAction {
      var jumpSequence = [SKTexture]();
    
      for i in 1...2 {
        let imageName = "jumpup\(i)";
        jumpSequence.append(SKTexture(imageNamed: imageName));
      }
    
      for i in 1...2 {
        let imageName = "jumpfall\(i)";
        jumpSequence.append(SKTexture(imageNamed: imageName));
      }
    
      let jump = SKAction.animate(with: jumpSequence, timePerFrame: TimeInterval(0.18), resize: true, restore: true);
    
      return jump;
    }
    

0 个答案:

没有答案