我在游戏中有一个角色,它应该会发射子弹。我已经为角色设置了所有内容,并设置了子弹穿过的路径。这是我正在使用的代码:
//The destination of the bullet
int x = myCharacter.position.x - 1000 * sin(myCharacter.zRotation);
int y = myCharacter.position.y + 1000 * cos(myCharacter.zRotation);
//The line to test the path
SKShapeNode* beam1 = [SKShapeNode node];
//The path
CGMutablePathRef pathToDraw = CGPathCreateMutable();
//The starting position for the path (i.e. the bullet)
//The NozzleLocation is the location of the nozzle on my character Sprite
CGPoint nozzleLoc=[self convertPoint:myCharacter.nozzleLocation fromNode:myCharacter];
CGPathMoveToPoint(pathToDraw, NULL, nozzleLoc.x, nozzleLoc.y);
CGPathAddLineToPoint(pathToDraw, NULL, x, y);
//The bullet
SKSpriteNode *bullet = [SKSpriteNode spriteNodeWithTexture:bulletTexture size:CGSizeMake(6.f, 6.f)];
bullet.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:3 center:bullet.position ];
[bullet.physicsBody setAffectedByGravity:NO];
[bullet.physicsBody setAllowsRotation:YES];
[bullet.physicsBody setDynamic:YES];
bullet.physicsBody.categoryBitMask = bulletCategory;
bullet.physicsBody.contactTestBitMask = boundsCategory;
//These log the correct locations for the character
//and the nozzle Location
NSLog(@"myposition: %@",NSStringFromCGPoint(myCharacter.position));
NSLog(@"nozloc: %@",NSStringFromCGPoint(nozzleLoc));
bullet.position = [bullet convertPoint:nozzleLoc fromNode:self];
[self addChild:bullet];
NSLog(@"Bullet Position: %@",NSStringFromCGPoint(bullet.position));
[bullet runAction:[SKAction followPath:pathToDraw duration:6.f]];
//I'm using this to test the path
beam1.path = pathToDraw;
[beam1 setStrokeColor:[UIColor redColor]];
[beam1 setName:@"RayBeam"];
[self addChild:beam1];
这是我从上面使用的 NSLogs 中得到的:
我的位置:{122.58448028564453, 109.20420074462891}
nozloc: {145.24272155761719, 77.654090881347656}
子弹位置:{145.24272155761719, 77.654090881347656}
所以一切都应该工作,对吧?但我遇到的问题是子弹是从稍微不同的位置射出的。你可以从下图中看到:
我对齐了角色,让子弹从中间的那个小方块开始。这样你就可以看到子弹应该从哪里开始的距离(在我的角色拿着的枪前面),以及屏幕中间的正方形。
子弹在一条直线上正确行进,并且线的角度与路径的角度相同(从图中可以看出路径和线子弹的形式是平行的)。当我移动我的线时,子弹也以同样的方式移动。我认为问题是节点之间的点转换,但我都尝试过
[self convertPoint:myCharacter.nozzleLocation fromNode:myCharacter]
[bullet convertPoint:nozzleLoc fromNode: self]
[self convertPoint:nozzleLoc toNode:bullet]
但是,它们都导致子弹的起点完全相同。你知道我为什么会遇到这个问题吗?setScale
是因为我正在使用(我将其设置为 0.3)缩小我的角色精灵吗?
非常感谢您的帮助。