菜鸟教程小白 发表于 2022-12-11 20:21:36

ios - Sprite Kit 所有对象仅出现在屏幕的右半部分


                                            <p><p>您好,我不是一个经验丰富的 ios 应用程序开发人员,我正在使用表情符号创建这个太空游戏,但是所有内容都在屏幕中间生成,当我使用加速度计移动玩家时,如果它正确的话消失,但如果我向左倾斜它会消失并从右循环返回,我该如何解决这个问题并为我的游戏 View 添加边框??</p>

<p>这是我的模拟器的截图
<a href="/image/SU7Gl.png" rel="noreferrer noopener nofollow"><img src="/image/SU7Gl.png" alt="In this screenshot, it shows how the emojis only spawn on the right half of the screen, and the player can&#39;t get to the left half either"/></a> </p>

<pre><code>import SpriteKit
import GameplayKit
import CoreMotion

class GameScene: SKScene, SKPhysicsContactDelegate {
    var player:SKSpriteNode!
    var emojis = [&#34;emoji1&#34;,&#34;emoji2&#34;, &#34;emoji3&#34;, &#34;emoji4&#34;, &#34;emoji5&#34;]
    var stars:SKEmitterNode!
    var scoreLabal: SKLabelNode!
    var score: Int = 0 {
      didSet {
            scoreLabal.text = &#34;Score: \(score)&#34;
      }
    }
    var gameTimer: Timer!
    let emojiCatagory: UInt32 = 0x1 &lt;&lt; 1
    let photonTorpedoCatagory: UInt32 = 0x1 &lt;&lt; 0
    let motionManger = CMMotionManager()
    var xAcceleration:CGFloat = 0
    override func sceneDidLoad() {




      stars = SKEmitterNode(fileNamed: &#34;Starfield&#34;)
      stars.position = CGPoint(x: 0, y: 1472)
      stars.advanceSimulationTime(10)
      self.addChild(stars)
      player = SKSpriteNode(imageNamed: &#34;Gun&#34;)


      player.position = CGPoint(x: self.frame.size.width / 32, y: (0 - (self.frame.size.height - player.size.height ) ) / 2 )
      print(&#34;The current deviec&#39;s screen height is \(self.frame.height), and the current device&#39;s width is \(self.frame.size.width) and the player&#39;s position is \(player.position)&#34;)


      self.addChild(player)

      self.physicsWorld.gravity = CGVector(dx: 0, dy: 0)
      self.physicsWorld.contactDelegate = self
      scoreLabal = SKLabelNode(text: &#34;Score: 0&#34;)
      scoreLabal.position = CGPoint(x:(self.frame.size.width - scoreLabal.frame.size.width ) / 2 - 20 , y: (self.frame.size.height - scoreLabal.frame.size.height ) / 2- 20 )
      scoreLabal.fontName = &#34;Symbol&#34;
      scoreLabal.fontColor = .white
      scoreLabal.fontSize = 36
      score = 0
      self.addChild(scoreLabal)


      gameTimer = Timer.scheduledTimer(timeInterval: 0.75, target: self, selector: #selector(setEmoji), userInfo: nil, repeats: true)



         motionManger.accelerometerUpdateInterval = 0.2
      motionManger.startAccelerometerUpdates(to: OperationQueue.current!) { (data:CMAccelerometerData?, error:Error?) in
            if let accelerometerData = data {
                let acceleration = accelerometerData.acceleration
                self.xAcceleration = CGFloat(acceleration.x) * 0.75 + self.xAcceleration * 0.25
            }

      }
    }
    @objc func setEmoji() {
      emojis = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: emojis) as!
      let emoji = SKSpriteNode(imageNamed: emojis)
      let randomPosition = GKRandomDistribution(lowestValue: 0, highestValue: Int(self.view!.bounds.width))
      print(&#34;this is the self . view&#34;, self.view!.bounds.width)
      print(&#34;this is the self the frame&#34;, self.frame.size.width)
      let position = CGFloat(randomPosition.nextInt())
      emoji.position = CGPoint(x: position, y: self.view!.bounds.height + emoji.size.height)
      emoji.physicsBody = SKPhysicsBody(rectangleOf: emoji.size)
      emoji.physicsBody?.isDynamic = true
      emoji.physicsBody?.categoryBitMask = emojiCatagory
      emoji.physicsBody?.contactTestBitMask = photonTorpedoCatagory
      emoji.physicsBody?.collisionBitMask = 0
      self.addChild(emoji)
      let animationduration = 5
      var acctionArray = ()
      acctionArray.append(SKAction.move(to: CGPoint(x: position, y: (0 - (self.frame.size.height) ) / 2 ), duration: TimeInterval(animationduration)))

      acctionArray.append(SKAction.removeFromParent())
      emoji.run(SKAction.sequence(acctionArray))
    }


    func fireTorpedo(soundFileName: String, positionOf: CGPoint) {


      self.run(SKAction.playSoundFileNamed(soundFileName, waitForCompletion: false))
      let torpedoNode = SKSpriteNode(imageNamed: &#34;torpedo&#34;)
      torpedoNode.position = player.position
      torpedoNode.position.y += 5
      torpedoNode.physicsBody = SKPhysicsBody(circleOfRadius: torpedoNode.size.width / 2)
      torpedoNode.physicsBody?.categoryBitMask = photonTorpedoCatagory
      torpedoNode.physicsBody?.contactTestBitMask = emojiCatagory
      torpedoNode.physicsBody?.collisionBitMask = 0
      self.addChild(torpedoNode)
      let animationDuration = 0.3
      var acctionArray = ()
      acctionArray.append(SKAction.move(to: CGPoint(x: positionOf.x , y: self.frame.size.height + 10 ), duration: TimeInterval(animationDuration)))
      print(&#34;positionOf.x value = \(positionOf.x)&#34;)
      print(&#34;positionOf value = \(positionOf)&#34;)
      print(&#34;positionOf.y value = \(positionOf.y)&#34;)

      acctionArray.append(SKAction.removeFromParent())
      torpedoNode.run(SKAction.sequence(acctionArray))



    }



    override func touchesEnded(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) {
      if let touch = touches.first {
            let PositionOfTouch = touch.location(in: view)
      }
      let PositionOfTouches = touches.first?.location(in: view)
      fireTorpedo(soundFileName: &#34;torpedo1&#34;, positionOf: PositionOfTouches!)
    }
    override func touchesMoved(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) {
      if let touch = touches.first {
            let PositionOfTouch = touch.location(in: view)
      }
      if score &gt; 100 &amp;&amp; score &lt; 200 {
                  let PositionOfTouches = touches.first?.location(in: view)
            fireTorpedo(soundFileName: &#34;torpedo2&#34;, positionOf: PositionOfTouches!)
    }
    }



    func torpedoCollideWithEmoji (torpedoNode: SKSpriteNode, emojiNode: SKSpriteNode) {
      let explosion = SKEmitterNode(fileNamed: &#34;Explosion&#34;)!
      explosion.position = emojiNode.position
      self.addChild(explosion)
      torpedoNode.removeFromParent()
      emojiNode.removeFromParent()
      self.run(SKAction.wait(forDuration: 2)) {
            explosion.removeFromParent()
      }

    score += 5
    }

    override func didSimulatePhysics() {
      player.position.x += xAcceleration * 50


      if player.position.x &lt; -20 {
            player.position = CGPoint(x: self.size.width, y: player.position.y)
      } else if player.position.x &gt; self.size.width * 20 {
            player.position = CGPoint(x:-20,y: player.position.y )
      }
    }




    func didBegin(_ contact: SKPhysicsContact) {
      var firstBody: SKPhysicsBody
      var secondBody: SKPhysicsBody

      if contact.bodyA.categoryBitMask &lt; contact.bodyB.categoryBitMask{
            firstBody = contact.bodyA
            secondBody = contact.bodyB
      }else {
            secondBody = contact.bodyA
            firstBody = contact.bodyB
      }

      if (firstBody.categoryBitMask &amp; photonTorpedoCatagory) != 0 &amp;&amp; (secondBody.categoryBitMask &amp; emojiCatagory ) != 0 {
            torpedoCollideWithEmoji(torpedoNode: firstBody.node as! SKSpriteNode, emojiNode: secondBody.node as! SKSpriteNode)
      }
    }


    override func update(_ currentTime: TimeInterval) {

}

}
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>你应该这样做给 View 添加一个边框:</p>

<pre><code>// 1
let borderBody = SKPhysicsBody(edgeLoopFrom: self.frame)
// 2
borderBody.friction = 0
// 3
self.physicsBody = borderBody
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - Sprite Kit 所有对象仅出现在屏幕的右半部分,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/51340877/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/51340877/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - Sprite Kit 所有对象仅出现在屏幕的右半部分