Created
November 30, 2009 07:18
-
-
Save hugowetterberg/245304 to your computer and use it in GitHub Desktop.
Cocos2D action that makes a node move towards a specific point at a set speed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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