我在将精灵节点旋转到触摸位置时遇到问题
这是我的代码:
#import "THMyScene.h"
#import <math.h>
#define SK_DEGREES_TO_RADIANS(__ANGLE__) ((__ANGLE__) * 0.01745329252f) // PI / 180
#define SK_RADIANS_TO_DEGREES(__ANGLE__) ((__ANGLE__) * 57.29577951f) // PI * 180
@implementation THMyScene
{
CGSize _winSize;
SKSpriteNode *_playerSprite;
}
-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
/* Setup your scene here */
self.backgroundColor = [SKColor colorWithRed:94.0/255.0 green:63.0/255.0 blue:107.0/255.0 alpha:1.0];
_winSize = CGSizeMake(self.size.width, self.size.height);
_playerSprite = [SKSpriteNode spriteNodeWithImageNamed:@"Player"];
_playerSprite.position = CGPointMake(368.0f, 160.0f);
[self addChild:_playerSprite];
}
return self;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
/* Called when a touch begins */
for (UITouch *touch in touches) {
CGPoint touchLocation = [touch locationInNode:self];
CGPoint spriteLocation = CGPointMake(_playerSprite.position.x, _playerSprite.position.y);
float xDistance;
float yDistance;
xDistance = powf(touchLocation.x - spriteLocation.x,2);
yDistance = powf(touchLocation.y - spriteLocation.y,2);
float angle = atan2f(yDistance,xDistance);
_playerSprite.zRotation = angle - SK_DEGREES_TO_RADIANS(90);
SKAction *moveAction = [SKAction moveTo:touchLocation duration:2];
[_playerSprite runAction: moveAction];
}
}
-(void)update:(CFTimeInterval)currentTime {
/* Called before each frame is rendered */
}
@end
关于问题可能是什么的任何建议
当我点击节点的右侧或顶部时,它正确地给我了方向 但是当我点击节点的左侧或底部时,方向位于相反的一侧。
答案 0 :(得分:1)
您需要根据触摸位置添加或减去90度。
float angle = atan2f(yDistance,xDistance);
if (spriteLocation.x > touchLocation.x) {
_playerSprite.zRotation = angle + M_PI_2; //M_PI_2 is 90 degrees in radians
} else {
_playerSprite.zRotation = angle - M_PI_2;
}