问题
I'm getting trouble trying to make the enemies in my game shoot bullets. The problem is the bullet texture doesn't appear to originate from the enemy texture. The bullet texture appears really far from the enemies' position. See the image below to understand what I'm talking about.
However, the hero-main character can shoot normally and the bullet texture works fine. I imagine that the problem is in the collision interaction, the enemies' textures are kept right between the walls but the the position stored keeps values outside the walls. That's so weird.Here the code of the shoot method
-(void)disparo
{
DDLogVerbose(@"DISPARO de un enemigo.");
NSLog(@"DISPARO de un enemigo.");
CGPoint location = cobra.position;
self->balasyExplosionesAtlas = [SKTextureAtlas atlasNamed:@"Clouds"];
SKSpriteNode *bullet = [SKSpriteNode spriteNodeWithTexture:[balasyExplosionesAtlas textureNamed:@"bala"]];
NSLog(@"Posicion DISPARO-ENEMIGO --> x %f -- y %f", cobra.position.x, cobra.position.y );
bullet.position = CGPointMake(cobra.position.x, cobra.position.y + cobra.size.height/2);
// bullet.position = location;
bullet.zPosition = 1;
bullet.scale = 0.8;
bullet.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:bullet.size];
bullet.physicsBody.dynamic = NO;
bullet.physicsBody.categoryBitMask = bulletCategory;
bullet.physicsBody.contactTestBitMask = enemyCategory;
bullet.physicsBody.collisionBitMask = 0;
SKAction *action = [SKAction moveToY:1000 duration:2];
SKAction *remove = [SKAction removeFromParent];
[bullet runAction:[SKAction sequence:@[action,remove]]];
[cobra addChild:bullet];
}
I'm adding the collision and contact definition for the enemies. I think that's correct, enemies, walls and the hero contact without trespassing like a ghost.
cobra.physicsBody.categoryBitMask = CollisionTypeEnemmy;
cobra.physicsBody.contactTestBitMask = CollisionTypeEnemmy | CollisionTypePlayer | CollisionTypeWall;
cobra.physicsBody.collisionBitMask = CollisionTypeEnemmy | CollisionTypePlayer | CollisionTypeWall;
And the general Collision definition parameters:
typedef NS_ENUM(uint32_t, CollisionType)
{
CollisionTypePlayer = 0x1 << 0,
CollisionTypeWall = 0x1 << 1,
CollisionTypeExit = 0x1 << 2,
CollisionTypeEnemmy = 0x1 << 3,
CollisionTypeBulletPlayer = 0x1 << 4,
CollisionTypeBulletEnemy = 0x1 << 5
};
回答1:
As the bullet is a child node of the enemy (cobra), its position is relative to the cobra's position. You're specifying the bullet position as cobra position - but instead, what it really does is offset the bullet even more. So, if you do not specify the position of the bullet (0, 0), it will be added right where the cobra is.
Change the bullet position to:
bullet.position = CGPointMake(0, 0 + cobra.size.height/2);
This should do the trick.
You can read more on this in the Sprite Kit Programming Guide (Building Your Scene -> A Node Provides a Coordinate System to Its Children).
来源:https://stackoverflow.com/questions/21362927/different-node-position-in-screen-and-value