I have two nodes. Player and Enemy. I want Enemy node to follow Player node once it's close enough and Enemy node would stop when it collides with Player node. And what I get is Enemy node goes on top of Player and both nodes gets pushed. I thought about somehow stopping Enemy node from moving on collision with Player but it seems to me like it should be a cleaner way.
(I move Enemy node by changing it possition on Update).
Here's my GameScene.sks:
-(void)didMoveToView:(SKView *)view {
player = [self childNodeWithName:@"character"];
enemy = [self childNodeWithName:@"enemy"];
self.physicsWorld.contactDelegate = self;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
for (UITouch *touch in touches) {
moveToTouch = [touch locationInNode:self];
SKNode *tile = [self nodeAtPoint:moveToTouch];
if([tile.name isEqualToString:@"tile"])
{
moveToTouch = tile.position;
}
}
}
-(void)update:(CFTimeInterval)currentTime {
[self walk:player to:moveToTouch];
if((SDistanceBetweenPoints(enemy.position, player.position) < 200))
{
[self walk:enemy to:player.position];
}
}
-(void)walk:(SKNode*)node to:(CGPoint)moveTo
{
if (CGPointEqualToPoint(moveTo, CGPointZero))
{
return;
}
if(round(moveTo.y) != round(node.position.y))
{
if(moveTo.y > node.position.y)
{
node.position = CGPointMake(node.position.x,node.position.y+2);
}
else if (moveTo.y < node.position.y)
{
node.position = CGPointMake(node.position.x,node.position.y-2);
}
}else if(round(moveTo.x) != round(node.position.x))
{
if(moveTo.x > node.position.x)
{
node.position = CGPointMake(node.position.x+2,node.position.y);
}
else if (moveTo.x < node.position.x)
{
node.position = CGPointMake(node.position.x-2,node.position.y);
}
}
float distance = SDistanceBetweenPoints(node.position, moveTo);
if (distance < 1.0){
moveToTouch = CGPointZero;
}
}
I don't know how you have it set up that your enemy follows the player. But you could try to
Use collision detection to know when the collided.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.