Useful Code Snippets

From Pixelwave

This section is currently under construction and will be updated soon.

Dragging an Image

the header file:
#import "Pixelwave.h"

@interface CodeSamplesRoot : PXSprite
{
	PXSprite *sprite;

	PXPoint *initialTouchPosition;
	PXPoint *initialImagePosition;
}

- (void) initializeAsRoot;

- (void) onTouchDown:(PXTouchEvent *)event;
- (void) onDrag:(PXTouchEvent *)event;
- (void) onTouchUp:(PXTouchEvent *)event;


@end



the .m file:


#import "CodeSamplesRoot.h"

@implementation CodeSamplesRoot

- (void) initializeAsRoot
{
	initialTouchPosition = [[PXPoint alloc] initWithX:0.0f andY:0.0f];
	initialImagePosition = [[PXPoint alloc] initWithX:0.0f andY:0.0f];

	[self.graphics beginFill:0x5fa7c9 alpha:1.0f];
	[self.graphics drawRectWithX:0.0f andY:0.0f andWidth:self.stage.stageWidth andHeight:self.stage.stageHeight];
	[self.graphics endFill];

	PXTexture *texture = [PXTexture textureWithContentsOfFile:@"image.jpg"];

	sprite = [PXSprite new];

	[sprite addChild:texture];

	[self addChild:sprite];

	[sprite addEventListenerOfType:PXTouchEvent_TouchDown listener:PXListener(onTouchDown:)];
}

- (void) dealloc
{
	[sprite removeEventListenerOfType:PXTouchEvent_TouchDown listener:PXListener(onTouchDown:)];

	[self onTouchUp:nil];

	[self removeChild:sprite];
	[sprite release];
	sprite = nil;

	[initialTouchPosition release];
	initialTouchPosition = nil;

	[initialImagePosition release];
	initialImagePosition = nil;

	[super dealloc];
}

// --- FUNCTIONS --- //

- (void) onTouchDown:(PXTouchEvent *)event
{
	[self addEventListenerOfType:PXTouchEvent_TouchUp listener:PXListener(onTouchUp:)];
	[self addEventListenerOfType:PXTouchEvent_TouchCancel listener:PXListener(onTouchUp:)];

	[self addEventListenerOfType:PXTouchEvent_TouchMove listener:PXListener(onDrag:)];

	initialTouchPosition.x = event.stageX;
	initialTouchPosition.y = event.stageY;

	initialImagePosition.x = sprite.x;
	initialImagePosition.y = sprite.y;
}

- (void) onDrag:(PXTouchEvent *)event
{
	sprite.x = initialImagePosition.x + (event.stageX - initialTouchPosition.x);
	sprite.y = initialImagePosition.y + (event.stageY - initialTouchPosition.y);
}

- (void) onTouchUp:(PXTouchEvent *)event
{
	[self removeEventListenerOfType:PXTouchEvent_TouchUp listener:PXListener(onTouchUp:)];
	[self removeEventListenerOfType:PXTouchEvent_TouchCancel listener:PXListener(onTouchUp:)];

	[self removeEventListenerOfType:PXTouchEvent_TouchMove listener:PXListener(onTouchUp:)];
}

@end

    This page was last modified on 12 August 2011, at 05:49.