Skip to content

Instantly share code, notes, and snippets.

@skyfe79
Forked from hugowetterberg/FollowAction.h
Created January 11, 2012 09:15
Show Gist options
  • Save skyfe79/1593857 to your computer and use it in GitHub Desktop.
Save skyfe79/1593857 to your computer and use it in GitHub Desktop.
Cocos2D action that makes a node move towards a specific point at a set speed
//
// FollowAction.h
// Battle Pong
//
// Created by Hugo Wetterberg on 2009-11-29.
// Copyright 2009 Good Old. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "cocos2d.h"
@interface FollowAction : Action {
float speed;
CGPoint goal;
}
@property (assign) float speed;
@property (assign) CGPoint goal;
- (id)initWithSpeed:(float)distancePerSecond goal:(CGPoint)aGoal;
@end
//
// FollowAction.m
// Battle Pong
//
// Created by Hugo Wetterberg on 2009-11-29.
// Copyright 2009 Good Old. All rights reserved.
//
#import "FollowAction.h"
@implementation FollowAction
@synthesize speed, goal;
- (id)initWithSpeed:(float)distancePerSecond goal:(CGPoint)aGoal {
if ((self = [super init])) {
goal = aGoal;
speed = distancePerSecond;
}
return self;
}
-(void) dealloc {
[super dealloc];
}
-(BOOL) isDone {
return NO;
}
-(void) step:(ccTime)dt {
CocosNode *t = (CocosNode *)self.target;
// Check so that we don't move too fast
float dy = goal.y - t.position.y;
float dx = goal.x - t.position.x;
if (dx != 0 || dy != 0) {
float d = sqrt((dy*dy)+(dx*dx));
float f = speed * dt / d;
if (f < 1) {
dy = dy * f;
dx = dx * f;
}
t.position = ccp(t.position.x + dx, t.position.y + dy);
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment