Drawing Trails

You can use Sparrow's SPrenderTexture to draw trails and create interesting effects. to do this we stamp an object repeatedly onto a render texture then stamp a colored quad on top to fade it out.

Try it with particles for some serious fun.

#import <Foundation/Foundation.h>
#import "Sparrow.h"
 
@interface SparrowTrails : SPStage{
	CGPoint lastTouch;
	CGPoint newTouch;
	SPImage *follower;
	SPQuad *fadeColor;
	SPRenderTexture *fadeTexture;
	SPImage *fadeImage;
}
 
- (void)update:(SPEnterFrameEvent*)event;
- (void)touched:(SPTouchEvent*)event;
 
@end
#import "SparrowTrails.h" 
 
@implementation SparrowTrails
 
- (id)initWithWidth:(float)width height:(float)height {
    self = [super initWithWidth:width height:height];
 
	// create the render texture to draw on
	fadeTexture = [[SPRenderTexture alloc] initWithWidth:320 height:480];
	[fadeTexture clearWithColor:0x000000 alpha:1];
	fadeImage = [SPImage imageWithTexture:fadeTexture];
	[self addChild:fadeImage];
 
	// create the object we are going to draw on the texture
	follower = [SPImage imageWithContentsOfFile:@"follower.png"];
	[self addChild:follower];
 
	// create something to log our touches
	lastTouch = CGPointMake(0, 0);
	newTouch = CGPointMake(0, 0);
 
	// this is the fade color we will use to fade out the trail
	fadeColor = [[SPQuad alloc] initWithWidth:320 height:480];
	fadeColor.color = 0x000000;
	fadeColor.alpha = .1;
 
	// add event listeners
	[self addEventListener:@selector(update:) atObject:self forType:SP_EVENT_TYPE_ENTER_FRAME];
	[self addEventListener:@selector(touched:) atObject:self forType:SP_EVENT_TYPE_TOUCH];
 
    return self;
}
 
- (void)update:(SPEnterFrameEvent*)event{
	// check to see if we have a new touch and draw the follower
	if(newTouch.x != lastTouch.x || newTouch.y != lastTouch.y){
		follower.x = newTouch.x - (follower.width/2);
		follower.y = newTouch.y - (follower.height/2);
		[fadeTexture drawObject:follower];
		lastTouch = CGPointMake(newTouch.x, newTouch.y);
	}
	// fade out the follower
	[fadeTexture drawObject:fadeColor];
}
 
- (void)touched:(SPTouchEvent*)event{
	// let's log our touches for the next enterframe event
	SPTouch *touchMove = [[event touchesWithTarget:self andPhase:SPTouchPhaseMoved] anyObject];
	if(touchMove){
		SPPoint *touchPos = [touchMove locationInSpace:self];
		newTouch = CGPointMake(touchPos.x, touchPos.y);
	}
}
 
- (void)dealloc{
	// cleanup
	[self removeEventListener:@selector(update:) atObject:self forType:SP_EVENT_TYPE_ENTER_FRAME];
	[self removeEventListener:@selector(touched:) atObject:self forType:SP_EVENT_TYPE_TOUCH];
	[fadeTexture release];
	[self removeChild:fadeImage];
	[self removeChild:follower];
	[self removeChild:fadeColor];
	[fadeColor dealloc];
	[super dealloc];
}
 
@end
  tutorials/drawing_trails.txt · Last modified: 2013/03/05 10:19 (external edit)
 
Powered by DokuWiki