我试图将玩家旋转到触摸状态。使用触摸移动功能,我将位置设置为变量。然后我调用一个函数。它工作但角度是关闭的。位置是全局变量,玩家是我要转的精灵。它关闭了大约15度。
func rotatePlayer(){
let angle = atan2(location!.y - player!.position.y , location!.x - player!.position.x)
player?.zRotation = angle
}
答案 0 :(得分:1)
根据SpriteKit Best Practices doc
使用符合SpriteKit坐标和旋转约定的游戏逻辑和艺术资产。这意味着将艺术品定位在右侧。如果您将图稿定向到其他方向,则需要在艺术品使用的约定和SpriteKit使用的约定之间转换角度。
由于默认宇宙飞船向上指向(当zRotation为0时),你需要将角度偏移90度(pi / 2弧度),以便当zRotation为零时船舶朝向右侧:
player?.zRotation = angle - CGFloat(M_PI_2)
或者,您可以将太空船旋转到右侧。要旋转图像,请单击Assets.xcassets,然后单击Spaceship。右键单击Spaceship图像,然后选择“在外部编辑器中打开”菜单项。这将在预览应用程序中打开图像。在预览中,选择工具>向右旋转并退出预览。通过旋转图稿,您的代码可以在不做任何更改的情况下工作。
答案 1 :(得分:0)
尝试这样的事情
//set sprite to image
Person = SKSpriteNode(imageNamed: "Person")
//set size
Person.size = CGSize(width: 40, height: 7)
//set position
Person.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2 + 120)
//rotate node 3.14 / 2 = to 90 degree angle
Person.zRotation = 3.14 / 2
Person.zPosition = 2.0
答案 2 :(得分:0)
使用方向约束将对象旋转到触摸位置:
// Create two global Sprite properties:
var heroSprite = SKSpriteNode(imageNamed:"Spaceship")
var invisibleControllerSprite = SKSpriteNode()
override func didMoveToView(view: SKView) {
// Create the hero sprite and place it in the middle of the screen
heroSprite.xScale = 0.15
heroSprite.yScale = 0.15
heroSprite.position = CGPointMake(self.frame.width/2, self.frame.height/2)
self.addChild(heroSprite)
// Define invisible sprite for rotating and steering behavior without trigonometry
invisibleControllerSprite.size = CGSizeMake(0, 0)
self.addChild(invisibleControllerSprite)
// Define a constraint for the orientation behavior
let rangeForOrientation = SKRange(constantValue: CGFloat(M_2_PI*7))
heroSprite.constraints = [SKConstraint.orientToNode(invisibleControllerSprite, offset: rangeForOrientation)]
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch: AnyObject in touches {
// Determine the new position for the invisible sprite:
// The calculation is needed to ensure the positions of both sprites
// are nearly the same, but different. Otherwise the hero sprite rotates
// back to it's original orientation after reaching the location of
// the invisible sprite
var xOffset:CGFloat = 1.0
var yOffset:CGFloat = 1.0
var location = touch.locationInNode(self)
if location.x>heroSprite.position.x {
xOffset = -1.0
}
if location.y>heroSprite.position.y {
yOffset = -1.0
}
// Create an action to move the invisibleControllerSprite.
// This will cause automatic orientation changes for the hero sprite
let actionMoveInvisibleNode = SKAction.moveTo(CGPointMake(location.x - xOffset, location.y - yOffset), duration: 0.2)
invisibleControllerSprite.runAction(actionMoveInvisibleNode)
// Optional: Create an action to move the hero sprite to the touch location
let actionMove = SKAction.moveTo(location, duration: 1)
heroSprite.runAction(actionMove)
}
}
教程:http://stefansdevplayground.blogspot.de/2014/11/how-to-implement-space-shooter-with.html