Detect objects, touchesmoved and UITouch - ios

I have a UIView on where i add balls with a ID. When i touch the ball with the ID 1 i draw a dashed line follows my finger.
The problem if when i move the finger to the other balls, i don't know how to detect these balls and check the ID they have. The what i need to happen is when i touch the next ball with the ID 2, the line finish draw and stay from ball 1 to ball 2, and create new one from 2 to finger, next.. 3 etc...
The code:
#import "DrawView.h"
#implementation DrawView
- (id)init
{
self = [super initWithFrame:CGRectMake(0, 0, 1024, 768)];
if (self) {
self.backgroundColor = [UIColor clearColor];
self.opaque = YES;
checkPointCircle = [[CheckPointCircle alloc] initWithPosX:315 posY:138 andNumber:1];
checkPointCircle.userInteractionEnabled = YES;
[self addSubview:checkPointCircle];
checkPointCircle = [[CheckPointCircle alloc] initWithPosX:706 posY:138 andNumber:2];
checkPointCircle.userInteractionEnabled = YES;
[self addSubview:checkPointCircle];
checkPointCircle = [[CheckPointCircle alloc] initWithPosX:315 posY:526 andNumber:3];
checkPointCircle.userInteractionEnabled = YES;
[self addSubview:checkPointCircle];
checkPointCircle = [[CheckPointCircle alloc] initWithPosX:706 posY:526 andNumber:4];
checkPointCircle.userInteractionEnabled = YES;
[self addSubview:checkPointCircle];
}
return self;
}
- (Line *)drawLine {
return drawLine;
}
- (void)setDrawLine:(Line *)line
{
drawLine = line;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CheckPointCircle * checkTouch = (CheckPointCircle *)touch.view;
if (touch.view.class == checkPointCircle.class) {
if ([checkTouch getObjectID] == 1) {
startTouchPoint = CGPointMake([checkTouch center].x, [checkTouch center].y);
endTouchPoint = [touch locationInView:self];
}
}
self.drawLine = [[Line alloc] initWithPoint:[touch locationInView:self]];
[self setNeedsDisplay];
}
-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(#"Cancelado");
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
UITouch *secondaryTouch = (UITouch *)[[[event touchesForView:checkPointCircle] allObjects] objectAtIndex: 0];
NSLog(#"Que toco: %# ", secondaryTouch.view);
if (touch.view.class == checkPointCircle.class) {
CheckPointCircle * checkTouch = (CheckPointCircle *)touch.view;
if ([checkTouch getObjectID] == 1) {
endTouchPoint = [touch locationInView:self];
}
}
[self setNeedsDisplay];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CheckPointCircle * checkTouch = (CheckPointCircle *)touch.view;
if (touch.view.class == checkPointCircle.class) {
if ([checkTouch getObjectID] == 1) {
endTouchPoint = [touch locationInView:self];
}
}
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect
{
[drawLine drawLineFrom:startTouchPoint to:endTouchPoint];
}
#end
How to detect the other balls to get the ID.
Can anybody help me?
Thanks!

The Apple documentation of class UIView (https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/UIView/UIView.html#//apple_ref/occ/instm/UIView/hitTest:withEvent:) lists two methods which will determine which view contains a hit/point:
– hitTest:withEvent:
– pointInside:withEvent:
Probably hitTest will help most: Its description reads "Returns the farthest descendant of the receiver in the view hierarchy (including itself) that contains a specified point.", so it even converts coordinates as needed.
If you check [self hitTest: [touch.locationInView self] withEvent: event] (or similar, no code completion here ;-)= in your touchesMoved: method, you should be able to detect when the finger is over any of the other circles.
Hope this helps, nobi

Related

Make bigger field for touch and drag node, objective c

I'm making small paddle node whom can touch and drag in defined area. The problem is that paddle is small wich makes for finger unresponsive. My question is how can i make area around node bigger without making node bigger. Here are What Iam working on:
- (id)initWithName:(NSString *)name
{
self = [super init];
if (self) {
self = [PaddleNode spriteNodeWithImageNamed: #"board.png"];
self.userInteractionEnabled = YES;
self.name = name;
self.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:self.frame.size];
self.physicsBody.dynamic = NO;
self.physicsBody.usesPreciseCollisionDetection = YES;
self.physicsBody.categoryBitMask = paddleCategory;
self.physicsBody.collisionBitMask = emptyCategory;
self.currentTouchValue = nil;
}
return self;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
self.previousTouchesTimestamp = event.timestamp;
for (UITouch *touch in touches) {
self.currentTouchValue = [NSValue valueWithNonretainedObject:touch];
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
self.currentTouchValue = nil;
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
for (UITouch *touch in touches) {
NSValue *key = [NSValue valueWithNonretainedObject:touch];
if ([key isEqualToValue:self.currentTouchValue]) {
CGPoint touchPoint = [touch locationInNode:self.scene];
CGPoint movePoint = CGPointMake(self.position.x, touchPoint.y);
if ([self withinParentFrame:movePoint])
self.position = movePoint;
}
}
}
- (BOOL)withinParentFrame:(CGPoint)point
{
CGFloat offset = self.size.height / 2;
if (point.y >= offset && point.y <= self.scene.frame.size.height - offset)
return YES;
else
return NO;
}
Edited : I read
UITouch Class Reference
documentation. As I understand that, I can't do it in touchesMoved, but I find my old project, were are same code, but there I can put my finger anywhere on screen, and node will move in nodes defined area.
Edited 2 This question is still unanswered and important to me!

how to stop my object to skip by clicking and move just by touch

I have some object on my screen view which moves by touch, but the problem is if I click somewhere else on my screen which has no object on, the last moved object skipped to that clicked position, anyone who know how I can be able to stop that? PostView contains code about my objects
in .h file
#property (weak, nonatomic) IBOutlet PostView *pv;
and .m file
- (void)viewDidLoad
{
[super viewDidLoad];
viewArray = [NSMutableArray arrayWithObjects: nil];
pv.frame = CGRectMake(10, 10, 100, 100);
pv.backgroundColor = [UIColor blackColor];
[viewArray insertObject:pv atIndex:0];
[self.view addSubview:pv];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint firstTouch = [touch locationInView:self.view];
for (PostView *view in viewArray) {
if (CGRectContainsPoint(view.frame, firstTouch)) {
toMove = view;
}
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:self.view];
toMove.center = location;
// [_delegate dragViewDidMove:self];
// toMove.center = currentTouch;
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
currentTouch = [touch locationInView:self.view];
toMove.center = currentTouch;
}
Set toView to null at the start of touchesBegan:. This ensures that if the user makes a touch that touches nothing (and so toView doesn't get set to anything deliberately), nothing will happen when the touch moves (the setCenter: message will be sent to null which will return null and have no side effects.)

How to detect subclass sprite touch

I subclass a sprite called newSprite.h / newSprite.m, and I add a sprite in it
CCSprite *nsprite = [CCSprite spriteWithFile:#"mouse.png"];
[self addChild: nsprite];
and in gamelayer.m, I add the following code
newSprite *newp = [newSprite node];
newp.position = ccp(actualX, actualY);
[self addChild:newp];
[_NSMutableArrayName addObject:newp];
when I use following code to detect which sprite i touched
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint location = [self convertTouchToNodeSpace: touch];
for (CCSprite *target in _NSMutableArrayName) {
if (CGRectContainsPoint(target.boundingBox, location)) {
CCLOG(#"yes i am touched");
}
}
}
but it doesn't work, the sprite can not be detected, so where is the wrong? please help me, thanks
Try using this:
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint location = [self convertTouchToNodeSpace:touch];
for (CCSprite *target in _NSMutableArrayName) {
CGSize size = node.contentSize;
CGRect r = CGRectMake(0.f, 0.f,
size.width, size.height);
if (CGRectContainsPoint(r, local)) {
CCLOG(#"yes i am touched");
}
}
}
You are trying to detect touches on sub sprite and giving the bounds of parent sprite.
First, take nsprite as class variable in NewSprite to keep its reference when you call it from GameLayer. Then try changing this method like:
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint location = [self convertTouchToNodeSpace: touch];
for (CCSprite *target in _NSMutableArrayName) {
CCSize size = target.nSprite.contentSize;
CCRect rect = CCRectMake(target.position.x - size.width/2, target.position.y - size.height/2, width, height);
if (CGRectContainsPoint(rect, location)) {
CCLOG(#"yes i am touched");
}
}
}

UIImageView touch handling

i have an image view as background image.
I am seeking that in some place on image view touches would be enabled.
I started with this:
- (id)initWithTouchPoint:(CGRect )point
{
self = [super init];
if (self) {
touchFrame = point;
[self setAccessibilityFrame:touchFrame];
}
return self;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/
-(BOOL)canResignFirstResponder{
return YES;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:self];
if (CGRectContainsPoint(touchFrame, touchLocation)) {
//[self setUserInteractionEnabled:NO];
}else{
//[self setUserInteractionEnabled:YES];
}
DLog(#"touchesBegan at x : %f y : %f",touchLocation.x,touchLocation.y);
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
}
Is it possible to let user touch over image view when user touches in touchFrame ?
Thank you.
Add UITapGestureRecognizer on UIImageView
UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self
action:#selector(handleGesture:)];
[gesture setNumberOfTapsRequired:1];
[imageView setUserInteractionEnabled:YES];
[imageView addGestureRecognizer:gesture];
Now within the HandleGesture Method :
-(void)handleGesture:(UITapGestureRecognizer *)_gesture
{
if (_gesture.state == UIGestureRecognizerStateEnded)
{
CGPoint touchedPoint = [_gesture locationInView:self.view];
}
}
you can check now wether the touchedPoint within the handleGesture method are in the specified area or not and you can perform your desired task accordingly
You can try having a boolean variable as a class member say BOOL allowTouch initialised with value NO:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:self];
if (CGRectContainsPoint(touchFrame, touchLocation)) {
allowTouch = YES;
}
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
if(allowTouch)
{
//handle moves here
}
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
allowTouch = NO;//you can put your condition too to end touches
}
It may help.

CGRect and touch

In this cocos2d app the nslog is not firing when I press the ccsprite. Could someone help me?
-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event{
NSMutableArray *targetsToDelete = [[NSMutableArray alloc] init];
for (CCSprite *target in _targets) {
CGRect targetRect = CGRectMake(target.position.x - (target.contentSize.width/2),
target.position.y - (target.contentSize.height/2),
27,
40);
CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
if (CGRectContainsPoint(targetRect, touchLocation)) {
NSLog(#"Moo cheese!");
}
}
return YES;
}
First of all be sure that you register the sprite for touches into the onEnter method for example:
- (void)onEnter
{
[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:defaultTouchPriority_ swallowsTouches:YES];
[super onEnter];
}
This will make your sprite touchable and so fire the event to the sprite when a user will press it.
Then refactor your code to make it more readable and test something like that:
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
NSArray *targetsToDelete = [self touchedSpritesAtLocation:touchLocation];
// Put your code here
// ...
return YES;
}
- (NSArray *)touchedSpritesAtLocation:(CGPoint)location
{
NSMutableArray *touchedSprites = [[NSMutableArray alloc] init];
for (CCSprite *target in _targets)
if (CGRectContainsPoint(target.boundingBox, location))
[touchedSprites addObject:target];
return [touchedSprites autorelease];
}
It should return the targets that have been touched.
In layer init method add this
self.isTouchEnabled = true;
Use this code for touch detection
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *myTouch = [touches anyObject];
CGPoint location = [myTouch locationInView:[myTouch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
CGRect rect = [self getSpriteRect:yourSprite];
if (CGRectContainsPoint(rect, location))
{
NSLog(#"Sprite touched\n");
}
}
To get sprite rect:
-(CGRect)getSpriteRect:(CCNode *)inSprite
{
CGRect sprRect = CGRectMake(
inSprite.position.x - inSprite.contentSize.width*inSprite.anchorPoint.x,
inSprite.position.y - inSprite.contentSize.height*inSprite.anchorPoint.y,
inSprite.contentSize.width,
inSprite.contentSize.height
);
return sprRect;
}

Resources