我是目标c的新手,所以仍然非常学习绳索。我有一款游戏,它使用TheSneakyNarwhal提供的代码在屏幕上制作虚拟操纵杆。 p>
https://github.com/TheSneakyNarwhal/SpriteKit-Joystick
我导入了git提供的文件,以下是与操纵杆实现相关的代码:
-(Joystick *)newJoystickNode {
SKSpriteNode *jsThumb = [SKSpriteNode spriteNodeWithImageNamed:@"joystick"];
SKSpriteNode *jsBackdrop = [SKSpriteNode spriteNodeWithImageNamed:@"dpad"];
Joystick *joystick = [Joystick joystickWithThumb:jsThumb andBackdrop:jsBackdrop];
joystick.position = CGPointMake(jsThumb.size.width, jsThumb.size.width);
joystick.name = @"playerJoystick";
//[joystick setScale:0.8];
return joystick;
}
-(void)joystickMovement
{
Joystick *joystick = (Joystick*)[self childNodeWithName:@"playerJoystick"];
SKSpriteNode *player = (SKSpriteNode*)[self childNodeWithName:@"hero"];
if ((joystick.velocity.x != 0 || joystick.velocity.y != 0) && (self.speed == 1))
{
player.position = CGPointMake(player.position.x + .1 *joystick.velocity.x, player.position.y + .1 * joystick.velocity.y);
}
}
-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
CADisplayLink *velocityTick = [CADisplayLink displayLinkWithTarget:self selector:@selector(joystickMovement)];
[velocityTick addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
[self addChild:[self newJoystickNode]];
[self addChild:[self newFireButtonNode]];
}
return self;
}
此操纵杆可在屏幕上移动角色并正常工作。我已按照上面git提供的说明进行操作。操纵杆位于屏幕的左下角。问题在某些情况下,如果我用操纵杆移动角色并触摸屏幕上的任何其他位置,这会干扰操纵杆并将其拉到右侧。
是否有人将此实现用于spriteKit操纵杆并出现此问题?或者有人知道为什么会发生这种情况吗?
答案 0 :(得分:0)
我之前遇到过同样的问题。我通过修改Joystick.m文件中的-touchesMoved方法修复了我的游戏。
只需使用-touchesMoved
Joystick.m
方法复制并替换以下代码即可
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
if (isTracking == YES)
{
for (UITouch *touch in touches)
{
CGPoint touchPoint = [touch locationInNode:self];
if (sqrtf(powf((touchPoint.x - self.anchorPointInPoints.x), 2) + powf((touchPoint.y - self.anchorPointInPoints.y), 2)) <= thumbNode.size.width)
{
CGPoint moveDifference = CGPointMake(touchPoint.x - self.anchorPointInPoints.x, touchPoint.y - self.anchorPointInPoints.y);
thumbNode.position = CGPointMake(self.anchorPointInPoints.x + moveDifference.x, self.anchorPointInPoints.y + moveDifference.y);
}
else
{
double vX = touchPoint.x - self.anchorPointInPoints.x;
double vY = touchPoint.y - self.anchorPointInPoints.y;
if (!(vX > 256 || vY > 256)) //Touchpoint should be within limits. Change the values to suit your situation.
{
double magV = sqrt(vX*vX + vY*vY);
double aX = self.anchorPointInPoints.x + vX / magV * thumbNode.size.width;
double aY = self.anchorPointInPoints.y + vY / magV * thumbNode.size.width;
thumbNode.position = CGPointMake(aX, aY);
}
}
}
velocity = CGPointMake(((thumbNode.position.x - self.anchorPointInPoints.x)), ((thumbNode.position.y - self.anchorPointInPoints.y)));
angularVelocity = -atan2(thumbNode.position.x - self.anchorPointInPoints.x, thumbNode.position.y - self.anchorPointInPoints.y);
[_delegate joystickMovement];
}
}