我有一个名为Balloon的单独SKNode类,如下所示。
import Foundation
import SpriteKit
class Balloon: SKNode {
init(image: SKSpriteNode) {
super.init()
let atlas = SKTextureAtlas(named: "balloons")
var textureArray = [SKTexture]()
self.physicsBody = SKPhysicsBody(texture: SKTexture(imageNamed: "red_balloon1"), size: CGSize(width: image.size.width, height: image.size.height))
self.physicsBody?.affectedByGravity = false
self.physicsBody?.categoryBitMask = balloonCategory
self.physicsBody?.contactTestBitMask = floorCategory
self.physicsBody?.collisionBitMask = floorCategory
self.position = CGPoint(x: 0, y: -UIScreen.main.bounds.height / 2)
self.zPosition = 1
for i in 1...atlas.textureNames.count {
let Name = "red_balloon\(i).png"
textureArray.append(SKTexture(imageNamed: Name))
}
image.run(SKAction.repeatForever(SKAction.animate(with: textureArray, timePerFrame: 0.1, resize: false, restore: true)))
self.addChild(image)
}
// Enables the ability to drag the ballon along the x axis
func move(touchLocation: CGPoint) {
if self.calculateAccumulatedFrame().contains(touchLocation) {
self.position.y = touchLocation.y
self.position.x = touchLocation.x
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
然后我在我的GameScene中使用这个类,如下所示。
let balloon = Balloon(image: SKSpriteNode(imageNamed: "red_balloon1"))
override func didMove(to view: SKView) {
self.addChild(balloon)
}
override func update(_ currentTime: TimeInterval) {
if let accelerometerData = motionManager.accelerometerData {
balloon.physicsBody?.velocity = CGVector(dx: accelerometerData.acceleration.y * 50, dy: accelerometerData.acceleration.x * 50)
}
}
基本上我基本上想做的是在纵向模式下使用应用程序并向左或向右平铺以移动我倾向于iPhone的节点。以下是我在Objective C中使用的内容,但我现在还不确定它是如何使用Swift 4的,或者是否有更好的东西。希望我提供了足够的信息,一些提示和任何帮助!
#define BALLOON 25
-(void)startAccelerometerData {
motionManager = [[CMMotionManager alloc] init];
motionManager.accelerometerUpdateInterval = 1/60.0;
[motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
valueX = accelerometerData.acceleration.x*26.0;
newX = (balloon.center.x +valueX);
if (newX > 320-BALLOON)
newX = 320-BALLOON;
else if (newX < 0+BALLOON)
newX = 0+BALLOON;
balloon.center = CGPointMake(newX, balloon.center.y);
} ];
}
答案 0 :(得分:2)
没关系,我明白了。
if let accelerometerData = motionManager.accelerometerData {
if UIDevice.current.orientation == UIDeviceOrientation.landscapeLeft {
balloon.physicsBody?.velocity = CGVector(dx: accelerometerData.acceleration.x * -500.0, dy: 0)
} else {
balloon.physicsBody?.velocity = CGVector(dx: accelerometerData.acceleration.x * 500.0, dy: 0)
}
}