collision detection with code - ios

I am new to programming and really need help now. I have been looking for an answer I think for the past two month. I'm using Xcode and objective-c. My question is about collision detection. There are thousands of example on what to do when 2 rectangle collide using CGRECT, such as alert or flip screen or play sound ext, but nothing anywhere about doing NOTHING lol! All I want is my object not going through the other object! That is all I want to keep dragging it on the screen. I just don't want the 2 object on top of each other and it seems like I'm the only online in the world that wants to do that because I can't find anything. So please help and since I'm new .. as simple as possible please so here :
#import "YellowDot.h"
#interface YellowDot ()
#end
#implementation YellowDot
#synthesize Dot;
#synthesize CollisionImage;
-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *Drag = [ [ event allTouches ] anyObject ];
Dot.center = [ Drag locationInView: self.view ];
[self checkCollison];
}
-(void) checkCollison
{
if (CGRectIntersectsRect(Dot.frame, CollisionImage.frame))
{
AudioServicesPlaySystemSound(playSoundId);
}
}
- (void)viewDidLoad
{
NSURL *SoundURL = [ NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"beep"ofType:#"wav"]];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)SoundURL, & playSoundId);
[super viewDidLoad];
// Do any additional setup after loading the view.
}
and here is the .h file :
#import <UIKit/UIKit.h>
#import <AudioToolbox/AudioToolbox.h>
#interface YellowDot : UIViewController
{
IBOutlet UIImageView *Dot;
IBOutlet UIImageView *CollisionImage;
SystemSoundID playSoundId;
}
#property (nonatomic, retain) UIImageView *Dot;
#property (nonatomic, retain) UIImageView *CollisionImage;
#end
So what could go in there ? It's already playing a sound when colliding as you can see but that's it. Dot is the image that I'm dragging around the screen and Collision image is the one that I want Dot to collide with but stop as a wall. Hope its clear enough ( I'm French, so sorry for the bad writing) :S Thank you.

Given that you're successfully detecting the collision, the answer would seem to be that if the move causes a collision, then don't update the object to the new position. Just don't update Dot.center. The sequence would be: get a touch event for the move, precompute the place where the object is going to be, if no collision, move it; if collision, don't update it's location.
Note that OpenGL might be better suited to this type of thing, given you're going to do a lot of it.

Related

MKMapview live car tracking

My requirement is to create an app that show live tracking of cab. Like famous car apps like Ola , uber and so on.
Please let me know how to update annotation , even for street turn and car reverse . How can simulate moving annotation using MKMapview. any library i have to use. I searched but i couldn't find any library
As I think the problem is smooth turning of the annotation on the map. As you can place your own custom image instead of the default blue dot.
for smooth turning you can use CMMotionManager as it gives you the acceleration so you can rotate the image by taking the reference of the annotation view. You can update for acceleration data by using update devicemotion data. As you get the useracceleration along x, y and z you can obtain the angle by tan function.This should solve your problem
code for getting the angle
[motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMDeviceMotion *motion, NSError *error) {
double angle = atan(motion.userAcceleration.x/motion.userAcceleration.y);
}];
The solution to this problem is quite trivial. If you having problem implementing this library, why not to do it yourself and learn something? You just create some type of Vehicle model class that stores coordinate and previous coordinate. To be able to display it on the map it would have to adhere to MKAnnotation protocol - implement: title, subtitle and coordinate. The newCoordinate position will be set by default upon obtaining position data from network. You need to track two values to successfully animate.
and thus implement something like this:
#interface Vehicle : NSObject <MKAnnotation>
#property (nonatomic, readonly, copy) NSString *title;
#property (nonatomic, readonly, copy) NSString *subtitle;
#property (nonatomic, assign) CLLocationCoordinate2D coordinate;
#property (nonatomic, assign) CLLocationCoordinate2D newCoordinate;
#end
Upon setting the newCoordinate you move the previous value from custom setter into the coordinate property. Once you do this, you would just animate the annotation as usual.
// new coordinate obtained from networking
- (void)setNewCoordinate:(CLLocationCoordinate2D)newCoordinate {
// implement the value moving part
_newCoordinate = newCoordinate;
}
But be careful when detecting taps on the animated annotation, because of the way it works. Annotation frame will be set when animation starts to the value of finished frame. You would need to hitTest taps on the presentationLayer of the annotation which gets displayed on the Screen during the animation.
To handle the taps override
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
}
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
}
animate with
[UIView animateWithDuration:0
delay:0
options:UIViewAnimationOptionCurveEaseIn
animations:^{
} completion:nil];
I am sorry but I can't post code here since I have previously implemented this for my employer and am bound by contract.

How to enable full screen Pan back for UINavigationController

From iOS7 apple provide a way to pan back UINavigationController, but it can only be done by swipe form the edge of the screen. How to enable full screen pan back gesture?
I really spend a lot of time trying to solve this problem, at last I found the way. I just ask a question and answer it myself to share the solution here.
Pls refer my blog to get more detail enter link description here
Demo code:
#import "TestNavigationController.h"
#interface _UINavigationInteractiveTransition
#end
#interface UINavigationController(Custom)
#property (strong, nonatomic) _UINavigationInteractiveTransition * _cachedInteractionController;
#end
#implementation TestNavigationController
{
UIPanGestureRecognizer *_p;
}
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"%#", self.interactivePopGestureRecognizer
);
_p = [[UIPanGestureRecognizer alloc]initWithTarget:self._cachedInteractionController action:#selector(handleNavigationTransition:)];
NSLog(#"%#", self._cachedInteractionController);
[self.view addGestureRecognizer:_p];
}
#end
EDIT NOTE:
This exposes Private APIs.

Presenting a SKSpritenode from different class ("addChild")

I have a Class for my Sprite and I'm trying to addChild from that class. The problem is it renders it and doesn't crash - I just can't see the image. I know the images position is right because created and added the child from the gameScene class and it worked and loaded.
I'm thinking this isn't working because its not subclass of SKscene that's why I added the main node from gameScene but didn't solve the problem.
I set up a "mainNode" node
keys is just the name of the sprite and its the class name
I know the image is being rendered its just not visible for some reason.
I know this because if I add no image name not "key_green" and change it to nothing. I get an console msg saying it can't find that image.
gameScene.m
#import "GameScene.h"
#import "Keys.h"
#implementation GameScene
#synthesize mainNode;
-(void)didMoveToView:(SKView *)view {
self.backgroundColor = [UIColor whiteColor];
mainNode = [SKNode node];
[self addChild:mainNode];
Keys * KeysOBJ =[[Keys alloc] init];
[KeysOBJ initKeys];
}
keys.h
#import <SpriteKit/SpriteKit.h>
#import "GameScene.h"
#interface Keys : SKSpriteNode{
SKSpriteNode * key1;
}
#property SKNode* mainNode;
-(void)initKeys;
-(void)loadKeys;
keys.m
#import "Keys.h"
#import "GameScene.h"
#implementation Keys{
}
#synthesize mainNode;
-(void)initKeys{
key1 = [SKSpriteNode spriteNodeWithImageNamed:#"key_red"];
key1.position = CGPointMake((self.frame.size.width)- (self.frame.size.width)+350, (self.frame.size.height)-(self.frame.size.height)+50);
[mainNode addChild:key1];
}
Your mainNode is nil in your Keys because you never set it before you call initKeys. This in theory will get it working.
Keys * KeysOBJ =[[Keys alloc] init];
KeysOBJ.mainNode = mainNode;
[KeysOBJ initKeys];
Also consider this
key1.position = CGPointMake((self.frame.size.width)- (self.frame.size.width)+350, (self.frame.size.height)-(self.frame.size.height)+50);
self doesn't have a size because you just called init and never supplied a texture or a size. Meaning your sprite location will likely be 350,50.
With that being said you are over complicating it. Your Keys shouldn't be a subclass of SKSpriteNode if you are never going to set a texture to it. It should be a SKNode.
Hopefully that makes some sense and gets you pointed back in the right direction.

How to improve the movement of an image within my ios App

Within my ios App I need to move an image but I am encountering some problems. I am able to move the image correctly to the calculated coordinates, but I need to click on the button that initiates the movement twice before it will appear in the right position, os on the first click the image will only show at the initial position without relocating to the new position.
This is my code:
(EDITED)
Viewcontroller.m
#import "ndpViewController.h"
#interface ndpViewController ()
#end
#implementation ndpViewController
#synthesize image;
-(void)viewDidLoad
{
}
-(void)dealloc
{
}
- (IBAction)calculatePush:(id)sender {
image.hidden=NO;
image.center=CGPointMake(376, 927);
}
- (void)viewDidUnload {
}
#end
Viewcontroller.h
#import <UIKit/UIKit.h>
#interface ndpViewController : UIViewController
{
IBOutlet UIImageView *image;
}
#property (weak, nonatomic) IBOutlet UIButton *calculate;
#property (nonatomic,retain) UIImageView *image;
#end
Any idea why I need to click twice before the image will relocate?. I don't need any kind of animation, just a little image (representing a cross) that will show at a specific point on top of a graphic.
Thank you very much and regards.
I dont exactly understand some of the code. But I think I understood your question which is 'How do I do something first click, and then something else on the second click?'
bool isFirstClick = true;
-(IBAction)CLickEvent:(id)sender{
if(isFirstClick){
//enter first click action here
isFirstClick = false;
}else{
//enter second click action here
isFirstClick = true;
}
}
You have not posted enough code to know for sure. But let me try it this way. What happens if zfw <= 26308 ?? It appears nothing. So in that case nothing moves. How does it EVER move when zfw is <= 26308?
NOTE:
Ok... the code as you have NOW posted it will NEVER relocate because you are always setting the position of the image to the same position on every click.
Actually the problem is even more weird than I thought. The image moves at first click if I type text into any text box within the app, but it will only move at the second click if I type in numbers at the any of those text boxes.
Any suggestion????

Handling touches within UIScrollview

I have a view that contains a UIScrollView. The UIScrollView contains an UIImageView (only one for now but there will be more latter). I want to be able to drag the UIImageView out of the UIScrollView and into the superview.
I have reviewed every similar question and example I can find online and still cant get my head around how this works.
At first I couldn't get touches to register all whithin the scrollview. After a lot of searching I have found a way to get touchesbegan to register as follows:
First I created a new view based project and in the auto-created "ViewController.h"
I created an IBOutlet named slider.
Then in the auto-created "ViewController.m" I created the UIScrollview.
In IB I added a UIScrollView to the storyboard then connected it to the "slider" IBOutlet.
Next I added class file to the projects. This new class is a subclass os UIImageView. I named this class "DragableImage" In the
Then in IB I dropped an image into the UIScrollview clicked on it and changed the class to "DragableImage"
In the DragableImage.m I voided touches began and simply told it to become hidden if clicked.
This works and the touch registers and makes the image disappear but how do I now add the new image to the main view and have it follow my finger?
This is what I have in the way of code:
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController {
IBOutlet UIScrollView *slider;
}
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[slider setScrollEnabled:YES];
[slider setContentSize:CGSizeMake(306, 1560)];
[slider setShowsVerticalScrollIndicator:NO];
slider.canCancelContentTouches = NO;
slider.delaysContentTouches = NO;
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
#end
DragableImage.h
#import <UIKit/UIKit.h>
#interface DragableImage : UIImageView
#end
DragableImage.m
#implementation DragableImage
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
self.hidden = YES;
}
#end
How to make this work?
There is one obvious problem that can arise here. Namely, how to tell the difference between dragging to scroll and dragging an image. The way I would handle this is to setup a tap and hold gesture recognizer (http://developer.apple.com/library/ios/#documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/GestureRecognizers/GestureRecognizers.html).
Once you detect a hold you could set it up so that further touches/gestures get routed to you drag and drop code. You can find a nice tutorial for that here:
http://www.ancientprogramming.com/2012/04/05/drag-and-drop-between-multiple-uiviews-in-ios/

Resources