使用 Swift 在 SpriteKit 中将精灵旋转到精灵位置不准确 [英] Rotate a sprite to sprite position not exact in SpriteKit with Swift

查看:18
本文介绍了使用 Swift 在 SpriteKit 中将精灵旋转到精灵位置不准确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试旋转播放器.使用 touches move 函数,我将位置设置为一个变量.然后我调用一个函数.它可以工作,但角度不对.位置是全局变量,玩家是我要转动的精灵.它偏离了大约 15 度.

I'm trying to rotate a player to the touch. Using the touches move function, I set the location to a variable. I then call a function. It works but the angle is off. Location is the global variable and player is the sprite I want to turn. It's off by about 15 degrees.

   func rotatePlayer(){

     let angle = atan2(location!.y - player!.position.y , location!.x - player!.position.x)
    player?.zRotation = angle
}

推荐答案

根据SpriteKit 最佳实践 doc

使用符合 SpriteKit 坐标和旋转约定的游戏逻辑和美术资源.这意味着将艺术品定向到右侧.如果您将艺术品定向到其他方向,则需要在艺术品使用的约定和 SpriteKit 使用的约定之间转换角度.

Use game logic and art assets that match SpriteKit’s coordinate and rotation conventions. This means orienting artwork to the right. If you orient the artwork in some other direction, you need to convert angles between the conventions used by the art and the conventions used by SpriteKit.

由于默认飞船指向上方(当 zRotation 为 0 时),您需要将角度偏移 90 度(pi/2 弧度),以便在 zRotation 为零时飞船朝向右侧:

Since the default spaceship points upward (when zRotation is 0), you will need to offset your angle by 90 degrees (pi/2 radians) so that the ship faces to the right when zRotation is zero:

player?.zRotation = angle - CGFloat(M_PI_2)

或者,您可以将宇宙飞船向右旋转.要旋转图像,请单击 Assets.xcassets,然后单击 Spaceship.右键单击 Spaceship 图像并选择 Open in External Editor 菜单项.这将在预览应用程序中打开图像.在预览中,选择工具 > 向右旋转并退出预览.通过旋转图稿,您的代码应该可以在没有任何更改的情况下运行.

Alternatively, you can rotate the spaceship to the right. To rotate the image, click on Assets.xcassets and then click on Spaceship. Right click on the Spaceship image and select the Open in External Editor menu item. This will open the image in the Preview app. In Preview, select Tools > Rotate Right and quit Preview. By rotating the artwork, your code should work without any changes.

这篇关于使用 Swift 在 SpriteKit 中将精灵旋转到精灵位置不准确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆