SpriteKit 初学者:鼠标节点未移动到随机位置

问题描述 投票:0回答:1

我是一个使用 SpriteKit 的初学者,我创建了一个名为 GameScene 的文件。它只包含一个称为鼠标的节点。我的目标是在应用程序启动时为鼠标设置动画并将其移动到随机位置。然而,虽然鼠标出现在模拟器屏幕上,但它并没有移动。我不确定我做错了什么。

import Foundation
import SpriteKit


class GameScene: SKScene {
    
    override func didMove(to view: SKView) {
        // Load the SKScene from the file
        if let scene = loadSKscene() {
            // Present the scene
            self.view?.presentScene(scene)
            
            // Find the "mouse" node from the loaded scene
            if let mouse = scene.childNode(withName: "mouse") {
                print("Mouse OK!")
                moveMouseRandomly(mouse)
            } else {
                print("Error: Mouse node not found!")
            }
            print("Scene size: \(scene.size)")
        } else {
            print("Error: Failed to load GameScene.sks")
        }
    }
    
    func loadSKscene() -> SKScene? {
        // Load GameScene.sks from the file
        guard let scene = SKScene(fileNamed: "GameScene") else {
            return nil
        }
        scene.scaleMode = .resizeFill
        return scene
    }
    
    func moveMouseRandomly(_ node: SKNode) {
        // Generate a random position within the scene's bounds
        let moveToRandomPosition = SKAction.move(to: randomPosition(), duration: 1.5)
        let wait = SKAction.wait(forDuration: 0.5)
        let sequence = SKAction.sequence([moveToRandomPosition, wait])
        let repeatForever = SKAction.repeatForever(sequence)
        
        // Run the action on the mouse node
        node.run(repeatForever)
        print("animate")
    }
    
    func randomPosition() -> CGPoint {
        // Generate a random position within the scene's bounds
        let x = CGFloat.random(in: 0...size.width)
        let y = CGFloat.random(in: 0...size.height)
        return CGPoint(x: x, y: y)
    }
}


struct ContentView: View {
  
    @State var scene = GameScene()
  
    var body: some View {
        SpriteView(scene: scene)
            .ignoresSafeArea()
    }
}

swift swiftui sprite-kit sprite game-development
1个回答
0
投票

你有两个问题。首先,

SKAction
对象会提前烘焙——这是为了效率。所以你的随机位置不会被重新计算。使用
SKAction.run
可以解决这个问题。其次,您应该将大小发送到操作函数中,因为该值会经常重新计算。

func moveMouseRandomly(_ node: SKNode, forSize scene_size:CGSize) {
    node.removeAction(forKey: "random movement")
    
    let moveToRandomPosition = SKAction.run {
        let x = CGFloat.random(in: 0...scene_size.width)
        let y = CGFloat.random(in: 0...scene_size.height)
        let p = CGPoint(x: x, y: y)
        node.run(SKAction.move(to: p, duration: 0.5))
    }
    let wait = SKAction.wait(forDuration: 1)

    let sequence = SKAction.sequence([moveToRandomPosition, wait])
    let repeatForever = SKAction.repeatForever(sequence)

    node.run(repeatForever, withKey: "random movement")
    print("animate")
}

并相应地更改

didMove(to view: SKView)

moveMouseRandomly(mouse, forSize: scene.size)
© www.soinside.com 2019 - 2024. All rights reserved.