0
votes

Hi all I am making a game where the enemy should not be able to go through walls and items in the game like for example if there is a wall, the enemy's character should not be able to go through it. however, I can't get the physics to work exactly right. I want the enemy be stopped if it tries to run into another sprite like a wall.

Thanks guys.

- (void) Enemy {
_Enemy = [SKSpriteNode spriteNodeWithImageNamed:@"enemy"];
_Enemy.position = CGPointMake(520, _Enemy.size.height/1.50);
[self addChild:_Enemy];

}

- (void) EnemyHomeWalls {
Wall = [SKSpriteNode spriteNodeWithImageNamed:@"Thewall@2x"];
wall.name = @"Thewall";
wall.position = CGPointMake(500, 150);
Wall.xScale = 0.12;
Wall.yScale = 0.12;
Wall.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
[self addChild:Wall];

}

1

1 Answers

0
votes

You need the enemy node to have a physicsBody as well:

_Enemy.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:_Enemy.size];

To prevent the node from being affected by gravity, you can set

_Enemy.physicsBody.affectedByGravity = NO;

Or, in the initWithSize method,

self.physicsWorld.gravity = CGVectorMake(0, 0);

You need to study the SKPhysicsBody class reference.