Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* AMS_Trail.h
- */
- #import <Foundation/Foundation.h>
- #import <SpriteKit/SpriteKit.h>
- @interface AMS_TrailPoint : NSObject
- @property CGVector m_vPosition;
- @property double m_fDistanceToNext;
- @end
- @interface AMS_Trail : NSObject
- @property int m_iMaxPoints;
- @property NSMutableArray* m_aPoints;
- - (void)addVector:(CGVector)vec;
- - (void)addPoint:(AMS_TrailPoint*)pt;
- - (CGVector)positionFromHead:(double)fDistance;
- @end
- /* AMS_Trail.m
- * (CGVectorAdditions is this: https://github.com/samgreen/CGVector-Awesome)
- */
- #import "AMS_Trail.h"
- #import "../CGVectorAdditions.h"
- @implementation AMS_TrailPoint
- - (instancetype)init
- {
- if(self = [super init]) {
- }
- return self;
- }
- @end
- @implementation AMS_Trail
- - (instancetype)init
- {
- if(self = [super init]) {
- self.m_iMaxPoints = 1000; // should be enough.. 1000 * (4 + 4 + 8) = up to 16 kB ^.^
- self.m_aPoints = [[NSMutableArray alloc] init];
- }
- return self;
- }
- - (void)addVector:(CGVector)vec
- {
- AMS_TrailPoint* tp = [[AMS_TrailPoint alloc] init];
- tp.m_vPosition = vec;
- if(self.m_aPoints.count > 0) {
- AMS_TrailPoint* tpFirst = [self.m_aPoints firstObject];
- tp.m_fDistanceToNext = CGVectorDistance(vec, tpFirst.m_vPosition);
- }
- [self addPoint:tp];
- }
- - (void)addPoint:(AMS_TrailPoint*)tp
- {
- if(self.m_iMaxPoints != 0 && self.m_aPoints.count >= self.m_iMaxPoints) {
- int iFromIndex = self.m_iMaxPoints - 2;
- [self.m_aPoints removeObjectsInRange:NSMakeRange(iFromIndex, self.m_aPoints.count - iFromIndex)];
- }
- [self.m_aPoints insertObject:tp atIndex:0];
- }
- - (CGVector)positionFromHead:(double)fDistance
- {
- for(int i=0; i<self.m_aPoints.count - 1; i++) {
- AMS_TrailPoint* tp = [self.m_aPoints objectAtIndex:i];
- if(fDistance > tp.m_fDistanceToNext) {
- fDistance -= tp.m_fDistanceToNext;
- } else {
- // lerp between last and current points
- AMS_TrailPoint* tpNext = [self.m_aPoints objectAtIndex:i + 1];
- CGVector vOffset = CGVectorDifference(tpNext.m_vPosition, tp.m_vPosition);
- vOffset = CGVectorNormalize(vOffset);
- vOffset = CGVectorMultiplyByScalar(vOffset, fDistance);
- return CGVectorSum(tp.m_vPosition, vOffset);
- }
- }
- // is last point?
- if(!self.m_aPoints.count == 0) {
- AMS_TrailPoint* tpLast = [self.m_aPoints lastObject];
- return tpLast.m_vPosition;
- }
- // list is empty
- return CGVectorMake(0, 0);
- }
- @end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement