我试图通过骑2个精灵来创造一个不断移动的背景。运行我的代码表明精灵已经以正确的大小添加到正确的位置。然而,精灵在屏幕上看不到。为什么会这样?我的代码在下面
import SpriteKit
import GameplayKit
import CoreMotion
class GameScene: SKScene, SKPhysicsContactDelegate{
var ship = SKSpriteNode()
var actionMoveRight = SKAction()
var actionMoveLeft = SKAction()
let shipCategory = 0x1 << 1
let obstacleCategory = 0x1 << 2
let backgroundVelocity : CGFloat = 3.0
var motionManager = CMMotionManager()
var background = SKSpriteNode.init(imageNamed: "background")
override func didMove(to view: SKView) {
// Making self delegate of physics world)
self.anchorPoint = CGPoint.init(x: 0.5, y: 0.5)
self.physicsWorld.gravity = CGVector.zero
self.physicsWorld.contactDelegate = self
createBG()
addShip()
}
override func update(_ currentTime: CFTimeInterval) {
moveBG()
}
func createBG(){
for i in 0...2{
background = SKSpriteNode.init(imageNamed: "background")
background.name = "background"
background.size = CGSize.init(width: (self.scene?.size.width)!, height: (self.scene?.size.height)!)
background.anchorPoint = self.anchorPoint
background.position = CGPoint.init(x: CGFloat(i) * background.size.width, y: (-(self.frame.size.height/2)))
background.zPosition = 0
self.addChild(background)
}
}
func moveBG(){
self.enumerateChildNodes(withName: "background", using: ({
(node, error) in
node.position.x -= 10
if node.position.x < (self.scene?.size.width)!{
node.position.x += (self.scene?.size.width)! * 2
}
}))
}
func addShip() {
// Initializing spaceship node
ship = SKSpriteNode(imageNamed: "Spaceship")
ship.setScale(0.2)
ship.isHidden = false
ship.zRotation = CGFloat(0)
// Adding SpriteKit physics body for collision detection
ship.physicsBody = SKPhysicsBody(rectangleOf: ship.size)
ship.physicsBody?.categoryBitMask = UInt32(shipCategory)
ship.physicsBody?.isDynamic = true
ship.physicsBody?.contactTestBitMask = UInt32(obstacleCategory)
ship.physicsBody?.collisionBitMask = 0
ship.name = "ship"
ship.position = CGPoint.init(x: 0, y: (-(self.frame.size.height/2)) + ship.size.height/2)
ship.zPosition = 1
self.addChild(ship)
actionMoveRight = SKAction.moveBy(x: 5, y: 0, duration: 0.2) //9
actionMoveLeft = SKAction.moveBy(x: -5 , y: 0, duration: 0.2) //10
if motionManager.isAccelerometerAvailable == true {
motionManager.startAccelerometerUpdates(to: OperationQueue.current!, withHandler:{
data, error in
if (data!.acceleration.y) < -0.05 {
self.ship.run(self.actionMoveLeft)
}
else if data!.acceleration.y > 0.05 {
self.ship.run(self.actionMoveRight)
}
})
}
}
}
答案 0 :(得分:0)
我假设背景节点大小与图像大小相同。我还假设场景大小与图像大小相同。如果是这种情况,请尝试以下操作。
let backTexture = SKTexture(imageNamed: "background")
let background = SKSpriteNode(texture: backTexture)
//background.size = CGSize.init(width: (self.scene?.size.width)!, height: (self.scene?.size.height)!)
//background.anchorPoint = self.anchorPoint
background.position = CGPoint(x: CGFloat(i) * background.size.width, y: 0))