0

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];

}

Ray
  • 161
  • 8

1 Answers1

0

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.

ZeMoon
  • 20,054
  • 5
  • 57
  • 98
  • I have tried that but what would happen is that all sudden the enemy's character would have some sort of gravity and it falls down to the bottom edge and stops there. – Ray Mar 23 '14 at 07:34
  • Almost but not quite. because what happens now is that if the enemy runs into the wall, it gets stuck there and won't move away. how can I solve that? thanks bud by the way. – Ray Mar 23 '14 at 07:37
  • How are you controlling the movement of the enemy sprite? – ZeMoon Mar 23 '14 at 07:39
  • its random. computer does that based on random x and y positions. – Ray Mar 23 '14 at 07:39
  • Yes, I get that. Please add the code for that. I am sure you are using SKActions which do not work well if you want your nodes to be simulated correctly using physics. – ZeMoon Mar 23 '14 at 07:41