i'm trying to implement this code for accelerometer use but i'm getting a compiler error:
stray /342, stray/200 ... for size,currentTouch, position object's and so on ...
why?
code:
//GravityObj.h
#interface GravityObj : UIView {
CGPoint position;
CGSize size;
CGPoint velocity;
NSTimer *objTimer;
NSString *pngName;
CGFloat bounce;
CGFloat gravity;
CGPoint acceleratedGravity;
CGPoint lastTouch;
CGPoint currentTouch;
BOOL dragging;
}
#property CGPoint position;
#property CGSize size;
#property CGPoint velocity;
#property(nonatomic,retain)NSString *pngName;
#property(nonatomic,retain)NSTimer *objTimer;
#property CGFloat bounce;
#property CGFloat gravity;
#property CGPoint acceleratedGravity;
#property CGPoint lastTouch;
#property CGPoint currentTouch;
#property BOOL dragging;
- (id)initWithPNG:(NSString*)imageName position:(CGPoint)p size:(CGSize)s;
- (void)update;
- (void)onTimer;
#end
//GravityObj.m
#import "GravityObj.h"
#implementation GravityObj
#synthesize position, size;
#synthesize objTimer;
#synthesize velocity;
#synthesize pngName;
#synthesize bounce;
#synthesize gravity, acceleratedGravity;
#synthesize lastTouch, currentTouch;
#synthesize dragging;
- (id)initWithPNG:(NSString*)imageName position:(CGPoint)p size:(CGSize)s {
if (self = [super initWithFrame:CGRectMake(p.x, p.y, s.width, s.height)]) {
[self setPngName:imageName];
[self setPosition:p];
[self setSize:s];
[self setBackgroundColor:[UIColor clearColor]];
// Set default gravity and bounce
[self setBounce:-0.9f];
[self setGravity:0.5f];
[self setAcceleratedGravity:CGPointMake(0.0, gravity)];
[self setDragging:NO];
UIImageView *prezzie = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, s.width, s.height)];
prezzie.image = [UIImage imageNamed:imageName];
[self addSubview:prezzie];
[prezzie release];
[[UIAccelerometer sharedAccelerometer] setDelegate:self];
}
return self;
}
- (void)update {
[self setNeedsDisplay];
if(dragging) return;
velocity.x += acceleratedGravity.x;
velocity.y += acceleratedGravity.y;
position.x += velocity.x;
position.y += velocity.y;
if(position.x + size.width >= 320.0) {
position.x = 320.0 – size.width;
velocity.x *= bounce;
}
else if(position.x <= 0.0) {
velocity.x *= bounce;
}
if(position.y + size.height >= 416.0) {
position.y = 416.0 – size.height;
velocity.y *= bounce;
}
else if(position.y <= 0.0) {
velocity.y *= bounce;
}
self.frame = CGRectMake(position.x, position.y, size.width, size.height);
}
- (void)onTimer {
[self update];
}
- (void)drawRect:(CGRect)rect {
// Drawing code
}
/* EVENTS */
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
acceleratedGravity.x = acceleration.x * gravity;
acceleratedGravity.y = -acceleration.y * gravity;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// First, lets check to make sure the timer has been initiated
if (objTimer == nil) {
objTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 / 30.0 target:self selector:#selector(onTimer) userInfo:nil repeats:YES];
}
UITouch *touch = [touches anyObject];
[self setCurrentTouch:[touch locationInView:self]];
CGFloat dx = currentTouch.x – position.x;
CGFloat dy = currentTouch.y – position.y;
CGFloat dist = sqrt(dx * dx + dy * dy);
if(dist < size.width) {
[self setVelocity:CGPointMake(0.0, 0.0)];
[self setDragging:YES];
}
[self setLastTouch:currentTouch];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
[self setCurrentTouch:[touch locationInView:self]];
[self setDragging:YES];
[self setVelocity:CGPointMake(currentTouch.x – lastTouch.x, currentTouch.y – lastTouch.y)];
[self setLastTouch:currentTouch];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[self setDragging:NO];
}
- (void)dealloc {
[objTimer release], objTimer = nil;
[pngName release], pngName = nil;
[super dealloc];
}
#end
It looks like the minus signs in some of your lines were Unicode characters that display as minuses and aren't. I copied your code into Xcode and got the same error. I then retyped each line that had the error and it worked.
Here's the fixed version (.m file only):
#implementation GravityObj
#synthesize position, size;
#synthesize objTimer;
#synthesize velocity;
#synthesize pngName;
#synthesize bounce;
#synthesize gravity, acceleratedGravity;
#synthesize lastTouch, currentTouch;
#synthesize dragging;
- (id)initWithPNG:(NSString*)imageName position:(CGPoint)p size:(CGSize)s {
if (self = [super initWithFrame:CGRectMake(p.x, p.y, s.width, s.height)]) {
[self setPngName:imageName];
[self setPosition:p];
[self setSize:s];
[self setBackgroundColor:[UIColor clearColor]];
// Set default gravity and bounce
[self setBounce:-0.9f];
[self setGravity:0.5f];
[self setAcceleratedGravity:CGPointMake(0.0, gravity)];
[self setDragging:NO];
UIImageView *prezzie = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, s.width, s.height)];
prezzie.image = [UIImage imageNamed:imageName];
[self addSubview:prezzie];
[prezzie release];
[[UIAccelerometer sharedAccelerometer] setDelegate:self];
}
return self;
}
- (void)update {
[self setNeedsDisplay];
if(dragging) return;
velocity.x += acceleratedGravity.x;
velocity.y += acceleratedGravity.y;
position.x += velocity.x;
position.y += velocity.y;
if(position.x + size.width >= 320.0) {
position.x = 320.0 - size.width;
velocity.x *= bounce;
}
else if(position.x <= 0.0) {
velocity.x *= bounce;
}
if(position.y + size.height >= 416.0) {
position.y = 416.0 - size.height;
velocity.y *= bounce;
}
else if(position.y <= 0.0) {
velocity.y *= bounce;
}
self.frame = CGRectMake(position.x, position.y, size.width, size.height);
}
- (void)onTimer {
[self update];
}
- (void)drawRect:(CGRect)rect {
// Drawing code
}
/* EVENTS */
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
acceleratedGravity.x = acceleration.x * gravity;
acceleratedGravity.y = -acceleration.y * gravity;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// First, lets check to make sure the timer has been initiated
if (objTimer == nil) {
objTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 / 30.0 target:self selector:#selector(onTimer) userInfo:nil repeats:YES];
}
UITouch *touch = [touches anyObject];
[self setCurrentTouch:[touch locationInView:self]];
CGFloat dx = currentTouch.x - position.x;
CGFloat dy = currentTouch.y - position.y;
CGFloat dist = sqrt(dx * dx + dy * dy);
if(dist < size.width) {
[self setVelocity:CGPointMake(0.0, 0.0)];
[self setDragging:YES];
}
[self setLastTouch:currentTouch];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
[self setCurrentTouch:[touch locationInView:self]];
[self setDragging:YES];
[self setVelocity:CGPointMake(currentTouch.x - lastTouch.x, currentTouch.y - lastTouch.y)];
[self setLastTouch:currentTouch];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[self setDragging:NO];
}
- (void)dealloc {
[objTimer release], objTimer = nil;
[pngName release], pngName = nil;
[super dealloc];
}
#end
If you get that error again, I found that viewing the file in FileMerge can help; it doesn't seem to know Unicode as well as Xcode.
You can pick up stray /342 /200 from copy/paste usually from pdf's sometimes html. Paste to a terminal and copy back out for a quick fix.
yes, i had also faced such types of error, it can be solved by just removing some unwanted formatted line space like gray focused line which is copied with content of code which you copied from other sites or web page or PDF file. It will definitely remove such types of error by removing extra formatted line or by just copy paste that code portion into notepad and original text copy back to your code..its done.!!!
Related
I have developed a carousel view that looks like the picture in post below
How do I calculate the position of a view animated from a 3-D carousel?
#pragma mark -
#pragma mark - VIEW LIFE CYCLE
- (void)viewDidLoad
{
[super viewDidLoad];
// VIEW FRAME
CGRect Frame = CGRectMake(-40, -40, 80, 80);
// CREATE 6 VIEWS
_CarouselView = [[NSMutableArray alloc] initWithCapacity:6];
int c = 5;
while(c--)
{
UIView *View = [[UIView alloc] initWithFrame:Frame];
View.backgroundColor = [UIColor colorWithRed:(c&4) ? 1.0 : 0.0 green:(c&2) ? 1.0 : 0.0 blue:(c&1) ? 1.0 : 0.0 alpha:1.0];
[_CarouselView addObject:View];
[self.view addSubview:View];
}
_CurrentAngle = _LastAngle = 0.0f;
[self setCarouselAngle:_CurrentAngle];
}
- (void)viewDidUnload
{
}
#pragma mark -
#pragma mark - VIEW TOUCH GESTURE
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
if(!_TrackingTouch)
{
_TrackingTouch = [touches anyObject];
[_AnimationTimer invalidate];
_AnimationTimer = nil;
_LastAngle = _CurrentAngle;
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
if([touches containsObject:_TrackingTouch])
{
// USE MOVEMENT TO DEVICE HOW MUCH TO ROTATE THE CAROUSEL
CGPoint LocationNow = [_TrackingTouch locationInView:self.view];
CGPoint LocationThen = [_TrackingTouch previousLocationInView:self.view];
_LastAngle = _CurrentAngle;
_CurrentAngle += (LocationNow.x - LocationThen.x) * 180.0f / self.view.bounds.size.width;
// the 180.0f / self.view.bounds.size.width just says "let a full width of my view
// be a 180 degree rotation"
// and update the view positions
[self setCarouselAngle:_CurrentAngle];
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
if([touches containsObject:_TrackingTouch])
{
_TrackingTouch = nil;
_AnimationTimer = [NSTimer scheduledTimerWithTimeInterval:0.04 target:self selector:#selector(animateAngle) userInfo:nil repeats:YES];
}
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
[self touchesEnded:touches withEvent:event];
}
#pragma mark -
#pragma mark - CAROUSEL ACTIONS
- (void)setCarouselAngle:(float)Angle
{
// ANGLE TO ADD AFTER EACH ELEM
_AngleToAdd = 360.0f / [_CarouselView count];
// APPLY TO ALL VIEWS
for(UIView *View in _CarouselView)
{
float AngleInRadians = Angle * M_PI / 180.0f;
// GET LOCATION
float x = (self.view.bounds.size.width * 0.5f) + 100.0f * sinf(AngleInRadians);
float y = ((self.view.bounds.size.height-200) * 0.5f) + 90.0f * cosf(AngleInRadians);
// ADJUST SCALE BETWEEN 0.75 0.25
float Scale = 0.75f + 0.25f * (cosf(AngleInRadians) + 1.0);
// APPLY TRANSFORMATION
View.transform = CGAffineTransformScale(CGAffineTransformMakeTranslation(x, y), Scale, Scale);
// TWEAK ALPHA
View.alpha = 0.1f + 0.5f * (cosf(AngleInRadians) + 1.0);
// SETTING Z POSITION
View.layer.zPosition = Scale;
// GET THE NEXT ANGLE
Angle += _AngleToAdd;
}
}
- (void)animateAngle
{
float AngleNow = _CurrentAngle;
_CurrentAngle += (_CurrentAngle - _LastAngle) * 0.97f;
_LastAngle = AngleNow;
// PUSH THE NEW ANGLE
[self setCarouselAngle:_CurrentAngle];
if(fabsf(_LastAngle - _CurrentAngle) < 0.001)
{
[_AnimationTimer invalidate];
_AnimationTimer = nil;
}
}
Everything works fine but i am having difficulty understanding where to place the pagination code
I hope this code can help you. You only need to create an ViewController and then copy-paste the code.
// CarruselViewController.m
//
// Created by Rosendo Castillo Perez on 2/25/14.
// Copyright (c) 2014 Fundtech. All rights reserved.
//
#import "CarruselViewController.h"
#interface CarruselViewController ()
{
NSMutableArray *_CarouselView;
CGFloat _CurrentAngle,_LastAngle, _AngleToAdd;
UITouch * _TrackingTouch;
NSTimer * _AnimationTimer;
}
#end
#implementation CarruselViewController
#pragma mark -
#pragma mark - VIEW LIFE CYCLE
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:(BOOL)animated];
// VIEW FRAME
CGRect Frame = CGRectMake(-40, -40, 80, 40);
// CREATE 6 VIEWS
_CarouselView = [[NSMutableArray alloc] initWithCapacity:6];
int c = 0;
while(c < 5)
{
UILabel *View = [[UILabel alloc] initWithFrame:Frame];
View.backgroundColor = [UIColor colorWithRed:(c&4) ? 1.0 : 0.0 green:(c&2) ? 1.0 : 0.0 blue:(c&1) ? 1.0 : 0.0 alpha:1.0];
[View setTextAlignment:NSTextAlignmentCenter];
[View setTextColor:[UIColor whiteColor]];
[View setFont:[UIFont boldSystemFontOfSize:14]];
[View setText:[NSString stringWithFormat:#"%d",c]];
[_CarouselView addObject:View];
[self.view addSubview:View];
c++;
}
_CurrentAngle = _LastAngle = 0.0f;
[self setCarouselAngle:_CurrentAngle];
}
#pragma mark -
#pragma mark - VIEW TOUCH GESTURE
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
if(!_TrackingTouch)
{
_TrackingTouch = [touches anyObject];
[_AnimationTimer invalidate];
_AnimationTimer = nil;
_LastAngle = _CurrentAngle;
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
if([touches containsObject:_TrackingTouch])
{
// USE MOVEMENT TO DEVICE HOW MUCH TO ROTATE THE CAROUSEL
CGPoint LocationNow = [_TrackingTouch locationInView:self.view];
CGPoint LocationThen = [_TrackingTouch previousLocationInView:self.view];
_LastAngle = _CurrentAngle;
_CurrentAngle += (LocationNow.x - LocationThen.x) * 180.0f / self.view.bounds.size.width;
// the 180.0f / self.view.bounds.size.width just says "let a full width of my view
// be a 180 degree rotation"
// and update the view positions
[self setCarouselAngle:_CurrentAngle];
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
if([touches containsObject:_TrackingTouch])
{
_TrackingTouch = nil;
_AnimationTimer = [NSTimer scheduledTimerWithTimeInterval:0.04 target:self selector:#selector(animateAngle) userInfo:nil repeats:YES];
}
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
[self touchesEnded:touches withEvent:event];
}
#pragma mark -
#pragma mark - CAROUSEL ACTIONS
- (void)setCarouselAngle:(float)Angle
{
// ANGLE TO ADD AFTER EACH ELEM
_AngleToAdd = 360.0f / [_CarouselView count];
// APPLY TO ALL VIEWS
for(UIView *View in _CarouselView)
{
float AngleInRadians = Angle * M_PI / 180.0f;
// GET LOCATION
float x = (self.view.bounds.size.width * 0.5f) + 100.0f * sinf(AngleInRadians);
float y = ((self.view.bounds.size.height-200) * 0.5f) + 40.0f * cosf(AngleInRadians);
// ADJUST SCALE BETWEEN 0.75 0.25
float Scale = 0.75f + 0.25f * (cosf(AngleInRadians) + 1.0);
// APPLY TRANSFORMATION
View.transform = CGAffineTransformScale(CGAffineTransformMakeTranslation(x, y), Scale, Scale);
// TWEAK ALPHA
View.alpha = 0.1f + 0.5f * (cosf(AngleInRadians) + 1.0);
// SETTING Z POSITION
View.layer.zPosition = Scale;
// GET THE NEXT ANGLE
Angle += _AngleToAdd;
}
}
- (void)animateAngle
{
float AngleNow = _CurrentAngle;
_CurrentAngle += (_CurrentAngle - _LastAngle) * 0.97f;
_LastAngle = AngleNow;
// PUSH THE NEW ANGLE
[self setCarouselAngle:_CurrentAngle];
if(fabsf(_LastAngle - _CurrentAngle) < 0.1)
{
_CurrentAngle = ((int)_CurrentAngle % 360);
if (_CurrentAngle < 0.0)
{
_CurrentAngle += 360.0;
}
[self setCarouselAngle:_CurrentAngle];
int currentAngle = (int) _CurrentAngle;
int angleToAdd = (int) _AngleToAdd;
int residuo = currentAngle % angleToAdd;
if (residuo != 0)
{
forward = (residuo > (angleToAdd / 2));
[_AnimationTimer invalidate];
_AnimationTimer = [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:#selector(centerAngle) userInfo:nil repeats:YES];
}
else
{
NSLog(#"angle: %d - index: %d",currentAngle,([_CarouselView count] - ((currentAngle / angleToAdd) % [_CarouselView count])));
}
}
}
BOOL forward = TRUE;
- (void)centerAngle
{
_CurrentAngle += (forward?1.0:-1.0);
[self setCarouselAngle:_CurrentAngle];
int currentAngle = (int) _CurrentAngle;
int angleToAdd = (int) _AngleToAdd;
int residuo = currentAngle % angleToAdd;
if (residuo == 0)
{
_LastAngle = _CurrentAngle = currentAngle;
[self setCarouselAngle:_CurrentAngle];
[_AnimationTimer invalidate];
_AnimationTimer = nil;
NSLog(#"angle: %d - index: %d",currentAngle,([_CarouselView count] - ((currentAngle / angleToAdd) % [_CarouselView count])));
}
}
#end
I want to draw a random design on uiview just like we are drawing on paint brush I want where user touch on screen start drawing. like if he wants to write ok in it than he can draw it.if he want to make duck or ball so he can make it. plz help me.
Try this.
In this, You will have to use self.view.frame wherever i have myPic.Frame.
In Header File:
#import <Foundation/Foundation.h>
#interface DrawView : UIView {
UIImage *myPic;
NSMutableArray *myDrawing;
}
-(void)drawPic:(UIImage *)thisPic;
-(void)cancelDrawing;
#end
and in Implementation File:
#import "DrawView.h"
#implementation DrawView
-(void)drawPic:(UIImage *)thisPic {
myPic = thisPic;
[myPic retain];
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect {
float newHeight;
float newWidth;
if (!myDrawing) {
myDrawing = [[NSMutableArray alloc] initWithCapacity:0];
}
CGContextRef ctx = UIGraphicsGetCurrentContext();
if (myPic != NULL) {
float ratio = myPic.size.height/460;
if (myPic.size.width/320 > ratio) {
ratio = myPic.size.width/320;
}
newHeight = myPic.size.height/ratio;
newWidth = myPic.size.width/ratio;
[myPic drawInRect:CGRectMake(0,0,newWidth,newHeight)];
}
if ([myDrawing count] > 0) {
CGContextSetLineWidth(ctx, 5);
for (int i = 0 ; i < [myDrawing count] ; i++) {
NSArray *thisArray = [myDrawing objectAtIndex:i];
if ([thisArray count] > 2) {
float thisX = [[thisArray objectAtIndex:0] floatValue];
float thisY = [[thisArray objectAtIndex:1] floatValue];
CGContextBeginPath(ctx);
CGContextMoveToPoint(ctx, thisX, thisY);
for (int j = 2; j < [thisArray count] ; j+=2) {
thisX = [[thisArray objectAtIndex:j] floatValue];
thisY = [[thisArray objectAtIndex:j+1] floatValue];
CGContextAddLineToPoint(ctx, thisX,thisY);
}
CGContextStrokePath(ctx);
}
}
}
}
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[myDrawing addObject:[[NSMutableArray alloc] initWithCapacity:4]];
CGPoint curPoint = [[touches anyObject] locationInView:self];
[[myDrawing lastObject] addObject:[NSNumber numberWithFloat:curPoint.x]];
[[myDrawing lastObject] addObject:[NSNumber numberWithFloat:curPoint.y]];
}
- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
CGPoint curPoint = [[touches anyObject] locationInView:self];
[[myDrawing lastObject] addObject:[NSNumber numberWithFloat:curPoint.x]];
[[myDrawing lastObject] addObject:[NSNumber numberWithFloat:curPoint.y]];
[self setNeedsDisplay];
}
- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
CGPoint curPoint = [[touches anyObject] locationInView:self];
[[myDrawing lastObject] addObject:[NSNumber numberWithFloat:curPoint.x]];
[[myDrawing lastObject] addObject:[NSNumber numberWithFloat:curPoint.y]];
[self setNeedsDisplay];
}
-(void)cancelDrawing {
[myDrawing removeAllObjects];
[self setNeedsDisplay];
}
- (void)dealloc {
[super dealloc];
[myPic release];
[myDrawing release];
}
#end
you will have to make your UIView a subClass of the above. And in your controller class.m file, you'll have to add and call these two methods.
I hope this works.
-(IBAction)clear {
[self.view cancelDrawing];
}
-(IBAction)saveDrawing
{
UIGraphicsBeginImageContext(self.view.bounds.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *finishedPic = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(finishedPic, self, #selector(exitProg:didFinishSavingWithError:contextInfo:), nil);
}
I have a sprite that rotates with touch. I need to be able to determine if it has rotated 360 degrees 3 times. Is there any way to tell?
Here is what I have so far
#import <Foundation/Foundation.h>
#import "cocos2d.h"
#import "GameScene.h"
#interface G : CCLayer {
CCSprite *g;
CGFloat gRotation;
}
#end
------------------------------------------
#import "G.h"
#implementation G
-(id) init
{
if ((self = [super init]))
{
CCLOG(#"%#: %#", NSStringFromSelector(_cmd), self);
g = [CCSprite spriteWithFile:#"g.png"];
[self addChild:g z:-1];
}
return self;
}
- (void)update:(ccTime)delta
{
g.rotation = gRotation;
}
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
}
- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint firstLocation = [touch previousLocationInView:[touch view]];
CGPoint location = [touch locationInView:[touch view]];
CGPoint touchingPoint = [[CCDirector sharedDirector] convertToGL:location];
CGPoint firstTouchingPoint = [[CCDirector sharedDirector] convertToGL:firstLocation];
CGPoint firstVector = ccpSub(firstTouchingPoint, g.position);
CGFloat firstRotateAngle = -ccpToAngle(firstVector);
CGFloat previousTouch = CC_RADIANS_TO_DEGREES(firstRotateAngle);
CGPoint vector = ccpSub(touchingPoint, g.position);
CGFloat rotateAngle = -ccpToAngle(vector);
CGFloat currentTouch = CC_RADIANS_TO_DEGREES(rotateAngle);
gRotation += currentTouch - previousTouch;
}
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
}
- (void) dealloc
{
CCLOG(#"%#: %#", NSStringFromSelector(_cmd), self);
[super dealloc];
}
#end
GameScene
#import "GameScene.h"
#import "MainMenu.h"
#import "G.h"
#implementation GameScene
+(CCScene *) scene
{
CCScene *scene = [CCScene node];
GameScene *layer = [GameScene node];
[scene addChild: layer];
return scene;
}
-(void) tapG: (id) sender
{
G *gView;
gView = [[G alloc] init];
gView.position = ccp(100, 100);
[self.parent addChild:gView z:1001];
[gView scheduleUpdate];
[gView release];
}
-(id) init
{
if ((self = [super init]))
{
tG = [CCMenuItemImage itemFromNormalImage:#"tp.png" selectedImage:#"tp.png" disabledImage:#"tpaperd.png" target:self selector:#selector(tapG:)];
gt = [CCMenu menuWithItems:tG, nil];
gt.position = ccp(210, 80);
[gt alignItemsHorizontallyWithPadding:10];
[self addChild:gt z:0];
}
return self;
}
- (void) dealloc
{
CCLOG(#"%#: %#", NSStringFromSelector(_cmd), self);
[super dealloc];
}
Can anyone help? Thanks in advance
cocos2d can take rotations more than 360. but if your going left and right then its a bit more complicated than just checking if sprite.rotation == 1080. if the rotation is happening on your touchesMoved method then what you should do is that you should record your highest rotation (rotation in right maybe) and lowest rotation (the other way) and then the difference should be bigger than 360*3. so add 2 class vars to your G layer float maxRot,minRot;
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
maxRot = mySprite.rotation; // here you set the ivars to defaults.
minRot = mySprite.rotation; // im setting them to your sprite initial rotation
} // incase it is not 0
at the end of your touchesMoved method you check for your conditions:
if (mySprite.rotation > maxRot)
maxRot = mySprite.rotation;
else if (mysprite.rotation < minRot)
minRot = mySprite.rotation;
if ((maxRot - minRot) >= (360*3)) {
// your condition is satisfied
}
i havent tested this so it could be just wrong.. but its worth a shot
EDIT:
the code above will not work unless the rotations are happening in the same direction.. it wont work for your right, left, right condition. I guess one way is to track the direction of your rotation in touchesMoved. so again youll need class vars
int numOfRots;
float previousRot, currentRot, accumRot;
BOOL isPositive, isPreviousPositive;
your touches methods:
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
previousRot = mySprite.rotation;
currentRot = mySprite.rotation;
accumRot = 0;
numOfRots = 0;
isPositive = NO;
isPreviousPositive = NO;
}
at the end of touchesMoved you will have the following:
currentRot = mySprite.rotation;
if (currentRot > previousRot)
isPositive = YES;
else
isPositive = NO;
if (isPositive != isPreviousPositive) {
// now we have a change in direction, reset the vars
accumRot = 0;
}
if (isPositive) {
accumRot += abs(currentRot - previousRot);
}
else {
accumRot += abs(previousRot - currentRot);
}
if (accumRot >= 360) {
//now we have one rotation in any direction.
numOfRots++;
//need to reset accumRot to check for another rot
accumRot = 0;
if (numOfRots == 3) {
//BINGO!!! now you have 3 full rotations
}
}
previousRot = currentRot;
isPreviousPositive = isPositive;
hope this helps
I want to rotate the below image on a center point using one finger touch...
And i want to display the value of the image with the label when I rotate the image using touch.
I have done the image rotation but the problem is that how to set the value of the image according to rotation.
The angle of the rotation is increase so i can not set the value.
Can any one help me?
The code is below
float fromAngle = atan2(firstLoc.y-imageView.center.y,
firstLoc.x-imageView.center.x);
NSLog(#"From angle:%f",fromAngle);
float toAngle = atan2( currentLoc.y-imageView.center.y,
currentLoc.x-imageView.center.x);
NSLog(#"to Angle:%f",toAngle);
// So the angle to rotate to is relative to our current angle and the
// angle through which our finger moved (to-from)
float newAngle =angle+(toAngle-fromAngle);
NSLog(#"new angle:%.2f",newAngle);
CGAffineTransform cgaRotate = CGAffineTransformMakeRotation(newAngle);
imageView.transform=cgaRotate;
angle = newAngle;
Can any one help me ?
Wasn't totally sure what you were after; but try out this code.
If you create a new View-based Application project called 'Rotation' and replace the code in RotationViewController.h and .m for the following you'll get a green block that you can rotate using your calculations. You can replace the green block UIView with your UIImageView, or anything else you want to spin.
RotationViewController.h
#import <UIKit/UIKit.h>
#interface RotationViewController : UIViewController
{
UIView* m_block;
UILabel* m_label;
CGPoint m_locationBegan;
float m_currentAngle;
}
- (float) updateRotation:(CGPoint)_location;
#end
RotationViewController.m
#import "RotationViewController.h"
double wrapd(double _val, double _min, double _max)
{
if(_val < _min) return _max - (_min - _val);
if(_val > _max) return _min - (_max - _val);
return _val;
}
#implementation RotationViewController
- (void)viewDidLoad
{
[super viewDidLoad];
CGRect blockFrame = CGRectMake(0, 0, 200, 200);
m_block = [[UIView alloc] initWithFrame:blockFrame];
m_block.backgroundColor = [UIColor greenColor];
m_block.center = self.view.center;
[self.view addSubview:m_block];
[m_block release];
CGRect labelFrame = CGRectMake(0, 0, 320, 30);
m_label = [[UILabel alloc] initWithFrame:labelFrame];
m_label.text = #"Loaded";
[self.view addSubview:m_label];
}
- (void) touchesBegan:(NSSet *)_touches withEvent:(UIEvent *)_event
{
UITouch* touch = [_touches anyObject];
CGPoint location = [touch locationInView:self.view];
m_locationBegan = location;
}
- (void) touchesMoved:(NSSet *)_touches withEvent:(UIEvent *)_event
{
UITouch* touch = [_touches anyObject];
CGPoint location = [touch locationInView:self.view];
[self updateRotation:location];
}
- (void) touchesEnded:(NSSet *)_touches withEvent:(UIEvent *)_event
{
UITouch* touch = [_touches anyObject];
CGPoint location = [touch locationInView:self.view];
m_currentAngle = [self updateRotation:location];
}
- (float) updateRotation:(CGPoint)_location
{
float fromAngle = atan2(m_locationBegan.y-m_block.center.y, m_locationBegan.x-m_block.center.x);
float toAngle = atan2(_location.y-m_block.center.y, _location.x-m_block.center.x);
float newAngle = wrapd(m_currentAngle + (toAngle - fromAngle), 0, 2*3.14);
CGAffineTransform cgaRotate = CGAffineTransformMakeRotation(newAngle);
m_block.transform = cgaRotate;
int oneInFifty = (newAngle*50)/(2*3.14);
m_label.text = [NSString stringWithFormat:#"Angle: %f 1in50: %i", newAngle, oneInFifty];
return newAngle;
}
#end
I am doing multi touch on UImageView means zoom in and zoom out on image view. I am using followng code but it doesn't work very well. Can anyone look at this code,
#import "ZoomingImageView.h"
#implementation ZoomingImageView
#synthesize zoomed;
#synthesize moved;
define HORIZ_SWIPE_DRAG_MIN 24
define VERT_SWIPE_DRAG_MAX 24
define TAP_MIN_DRAG 10
CGPoint startTouchPosition;
CGFloat initialDistance;
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
// Initialization code
moved = NO;
zoomed = NO;
}
return self;
}
- (void)drawRect:(CGRect)rect {
// Drawing code
}
- (void)dealloc {
if([timer isValid])
[timer invalidate];
[super dealloc];
}
- (void) setImage: (UIImage*)img
{
zoomed = NO;
moved = NO;
self.transform = CGAffineTransformIdentity;
[super setImage:img];
}
- (CGFloat)distanceBetweenTwoPoints:(CGPoint)fromPoint toPoint:(CGPoint)toPoint {
float x = toPoint.x - fromPoint.x;
float y = toPoint.y - fromPoint.y;
return sqrt(x * x + y * y);
}
- (CGFloat)scaleAmount: (CGFloat)delta {
CGFloat pix = sqrt(self.frame.size.width * self.frame.size.height);
CGFloat scale = 1.0 + (delta / pix);
return scale;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
if([timer isValid])
[timer invalidate];
moved = NO;
switch ([touches count]) {
case 1:
{
// single touch
UITouch * touch = [touches anyObject];
startTouchPosition = [touch locationInView:self];
initialDistance = -1;
break;
}
default:
{
// multi touch
UITouch *touch1 = [[touches allObjects] objectAtIndex:0];
UITouch *touch2 = [[touches allObjects] objectAtIndex:1];
initialDistance = [self distanceBetweenTwoPoints:[touch1 locationInView:self]
toPoint:[touch2 locationInView:self]];
break;
}
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch1 = [[touches allObjects] objectAtIndex:0];
if([timer isValid])
[timer invalidate];
/*if ([touches count] == 1) {
CGPoint pos = [touch1 locationInView:self];
self.transform = CGAffineTransformTranslate(self.transform, pos.x - startTouchPosition.x, pos.y - startTouchPosition.y);
moved = YES;
return;
}****/
if ((initialDistance > 0) && ([touches count] > 1)) {
UITouch *touch2 = [[touches allObjects] objectAtIndex:1];
CGFloat currentDistance = [self distanceBetweenTwoPoints:[touch1 locationInView:self]
toPoint:[touch2 locationInView:self]];
CGFloat movement = currentDistance - initialDistance;
NSLog(#"Touch moved: %f", movement);
CGFloat scale = [self scaleAmount: movement];
self.transform = CGAffineTransformScale(self.transform, scale, scale);
// }
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch1 = [[touches allObjects] objectAtIndex:0];
if ([touches count] == 1) {
// double tap to reset to default size
if ([touch1 tapCount] > 1) {
if (zoomed) {
self.transform = CGAffineTransformIdentity;
moved = NO;
zoomed = NO;
}
return;
}
}
else {
// multi-touch
UITouch *touch2 = [[touches allObjects] objectAtIndex:1];
CGFloat finalDistance = [self distanceBetweenTwoPoints:[touch1 locationInView:self]
toPoint:[touch2 locationInView:self]];
CGFloat movement = finalDistance - initialDistance;
NSLog(#"Final Distance: %f, movement=%f",finalDistance,movement);
if (movement != 0) {
CGFloat scale = [self scaleAmount: movement];
self.transform = CGAffineTransformScale(self.transform, scale, scale);
NSLog(#"Scaling: %f", scale);
zoomed = YES;
}
}
}
- (void)singleTap: (NSTimer*)theTimer {
// must override
}
- (void)animateSwipe: (int) direction {
// must override
}
It is not working fine on device. can anyone tell that where i am wrong.
When you use any CGAffinTransform.... the value of the frame property becomes undefined. In your code you are using the frame.size.width and frame.size.height to calculate the change in size. After the first iteration of CGAffinTransformScale you would not get the right scale factor. According to the documentation bounds would be the right property for scale calculations.