zooming using pinch but not using transform methods - objective-c

I'm trying to zoom the drawing on the context based on pinching in and out. This is working perfectly, but it will always zoom from the origin (top left). This doesn't give the nice effect you get in other applications and is really annoying. The old zooming method is as follows:
- (IBAction)handlePinchGesture:(UIGestureRecognizer *)sender {
UIPinchGestureRecognizer *pinch = (UIPinchGestureRecognizer *)sender;
if ([pinch scale] > zoomLevel + MAX_ZOOM_PER_CALL) {
[pinch setScale: zoomLevel + MAX_ZOOM_PER_CALL];
}
if ([pinch scale] < zoomLevel - MAX_ZOOM_PER_CALL) {
[pinch setScale:zoomLevel - MAX_ZOOM_PER_CALL];
}
float prevZoomLevel = zoomLevel;
CGFloat factor = [pinch scale];
zoomLevel = factor;
if (zoomLevel < MIN_ZOOM_LEVEL) {
zoomLevel = MIN_ZOOM_LEVEL;
}
if (zoomLevel > MAX_ZOOM_LEVEL) {
zoomLevel = MAX_ZOOM_LEVEL;
}
//The next piece of code is added here
[self setNeedsDisplay];
}
The actual zooming is done in the drawing methods of the parts that are shown on the context. I was thinking of changing the origin of the screen (that is the relative origin to the items that are to be drawn) so it would simulate this. But it is not working at all, this is what i have right now:
float dZoomLevel = zoomLevel - prevZoomLevel;
if (dZoomLevel != 0) {
CGPoint touchLocation = [pinch locationInView:self];
CGPoint zoomedTouchLocation = CGPointMake(touchLocation.x * prevZoomLevel, touchLocation.y * prevZoomLevel);
CGPoint newLocation = CGPointMake(touchLocation.x * zoomLevel, touchLocation.y * zoomLevel);
float dX = ( newLocation.x - zoomedTouchLocation.x );
float dY = ( newLocation.y - zoomedTouchLocation.y );
_originX += roundf(dX);
_originY += roundf(dY);
}
The origin is taken from the xml (the smallest x and y of all the elements). It will usually be something between 12000 and 20000 but could in theory be between 0 and 100000.
I'm not sure if I've made myself clear, but if you need any information or don't understand something just ask me and i'll try to reply ASAP. Thanks in advance!

I found the answer myself. The way one needs to zoom in my case is by zooming from the point of the touch. So when the x and y coordinates get zoomed do this:
x -= pinchLocation.x;
y -= pinchLocation.y;
x *= zoomLevel;
y *= zoomLevel;
x += pinchLocation.x;
y += pinchLocation.y;
or in short:
x = (x - pinchLocation.x) * zoomLocation + pinchLocation.x;
y = (y - pinchLocation.y) * zoomLocation + pinchLocation.y;
now x and y are on the correct location!!

Related

More Precise CGPoint for UILongPressGestureRecognizer

I am using a UILongPressGestureRecognizer which works perfectly but the data I get is not precise enough for my use case. CGPoints that I get are rounded off I think.
Example points that I get: 100.5, 103.0 etc. The decimal part is either .5 or .0 . Is there a way to get more precise points? I was hoping for something like .xxxx as in '100.8745' but .xx would do to.
The reason I need this is because I have a circular UIBezierPath, I want to restrict a drag gesture to only that circular path. The item should only be draggable along the circumference of this circle. To do this I calculated 720 points on the circle's boundary using it's radius. Now these points are .xxxx numbers. If I round them off, the drag is not as smooth around the middle section of the circle.This is because in the middle section, the equator, the points on the x-coordinate are very close together. So when I rounded of the y-coordinate, I lost a lot of points and hence the "not so smooth" drag action.
Here is how I calculate the points
for (CGFloat i = -154;i<154;i++) {
CGPoint point = [self pointAroundCircumferenceFromCenter:center forX:i];
[bezierPoints addObject:[NSValue valueWithCGPoint:point]];
i = i - .5;
}
- (CGPoint)pointAroundCircumferenceFromCenter:(CGPoint)center forX:(CGFloat)x
{
CGFloat radius = 154;
CGPoint upperPoint = CGPointZero;
CGPoint lowerPoint = CGPointZero;
//theta used to be the x variable. was first calculating points using the angle
/* point.x = center.x + radius * cosf(theta);
point.y = center.y + radius * sinf(theta);*/
CGFloat y = (radius*radius) - (theta*theta);
upperPoint.x = x+156;
upperPoint.y = 230-sqrtf(y);
lowerPoint.x = x+156;
lowerPoint.y = sqrtf(y)+230;
NSLog(#"x = %f, y = %f",upperPoint.x, upperPoint.y);
[lowerPoints addObject:[NSValue valueWithCGPoint:lowerPoint]];
[upperPoints addObject:[NSValue valueWithCGPoint:upperPoint]];
return upperPoint;
}
I know the code is weird I mean why would I add the points into arrays and return one point back.
Here is how I restrict the movement
-(void)handleLongPress:(UILongPressGestureRecognizer *)recognizer{
CGPoint finalpoint;
CGPoint initialpoint;
CGFloat y;
CGFloat x;
CGPoint tempPoint;
if(recognizer.state == UIGestureRecognizerStateBegan){
initialpoint = [recognizer locationInView:self.view];
CGRect rect = CGRectMake(initialpoint.x, initialpoint.y, 40, 40);
self.hourHand.frame = rect;
self.hourHand.center = initialpoint;
NSLog(#"Long Press Activated at %f,%f",initialpoint.x, initialpoint.y );
}
else if (recognizer.state == UIGestureRecognizerStateChanged){
CGPoint currentPoint = [recognizer locationInView:self.view];
x = currentPoint.x-initialpoint.x;
y = currentPoint.y-initialpoint.y;
tempPoint = CGPointMake( currentPoint.x, currentPoint.y);
NSLog(#"temp point ::%f, %f", tempPoint.x, tempPoint.y);
tempPoint = [self givePointOnCircleForPoint:tempPoint];
self.hourHand.center = tempPoint;
}
else if (recognizer.state == UIGestureRecognizerStateEnded){
// finalpoint = [recognizer locationInView:self.view];
CGRect rect = CGRectMake(tempPoint.x, tempPoint.y, 20, 20);
self.hourHand.frame = rect;
self.hourHand.center = tempPoint;
NSLog(#"Long Press DeActivated at %f,%f",tempPoint.x, tempPoint.y );
}
}
-(CGPoint)givePointOnCircleForPoint:(CGPoint) point{
CGPoint resultingPoint;
for (NSValue *pointValue in allPoints){
CGPoint pointFromArray = [pointValue CGPointValue];
if (point.x == pointFromArray.x) {
// if(point.y > 230.0){
resultingPoint = pointFromArray;
break;
// }
}
}
Basically, I taking the x-coordinate of the "touched point" and returning the y by comparing it to the array of points I calculated earlier.
Currently this code works for half a circle only because, each x has 2 y values because it's a circle, Ignore this because I think this can be easily dealt with.
In the picture, the white circle is the original circle, the black circle is the circle of the points I have from the code+formatting it to remove precision to fit the input I get. If you look around the equator(red highlighted part) you will see a gap between the next points. This gap is my problem.
To answer your original question: On a device with a Retina display, one pixel is 0.5 points, so 0.5 is the best resolution you can get on this hardware.
(On non-Retina devices, 1 pixel == 1 point.)
But it seems to me that you don't need that points array at all. If understand the problem correctly, you can use the following code to
"restrict" (or "project") an arbitrary point to the circumference of the circle:
CGPoint center = ...; // Center of the circle
CGFloat radius = ...; // Radius of the circle
CGPoint point = ...; // The touched point
CGPoint resultingPoint; // Resulting point on the circumference
// Distance from center to point:
CGFloat dist = hypot(point.x - center.x, point.y - center.y);
if (dist == 0) {
// The touched point is the circle center.
// Choose any point on the circumference:
resultingPoint = CGPointMake(center.x + radius, center.y);
} else {
// Project point to circle circumference:
resultingPoint = CGPointMake(center.x + (point.x - center.x)*radius/dist,
center.y + (point.y - center.y)*radius/dist);
}

Zooming core plot along Y-axis and X-axis Independently

I am Using the below code to scroll my core plot along X-axis Y-axis and zoom. Its working fine. But I when i zoom my core plot, it zooms in both the directions. I want the plot to zoom along X if I pinch along x-direction and zoom Y if pinch along Y-direction. Can someone help me with this please.
-(CGPoint)plotSpace:(CPTPlotSpace *)space willDisplaceBy:(CGPoint)displacement
{
return CGPointMake(displacement.x, displacement.y);
}
-(CPTPlotRange *)plotSpace:(CPTPlotSpace *)space willChangePlotRangeTo:(CPTPlotRange *)newRange forCoordinate:(CPTCoordinate)coordinate
{
// Adjust axis to keep them in view at the left and bottom;
// adjust scale-labels to match the scroll.
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)self.hostView.hostedGraph.axisSet;
if (coordinate == CPTCoordinateX) {
axisSet.yAxis.orthogonalCoordinateDecimal = newRange.location;
}
else {
axisSet.yAxis.titleLocation = CPTDecimalFromFloat(newRange.locationDouble + (newRange.lengthDouble / 2.0F));
}
return newRange;
}
The easiest way to keep the axes and title in the correct position is to use the axisConstraints for the axes and leave the titleLocation at it's default of NAN. This will relieve your delegate of responsibility for updating those items and you can focus on the zooming.
Of those two delegate methods, you only need -plotSpace:willChangePlotRangeTo:forCoordinate:. The other one is only called when scrolling.
Decide whether you want to allow the zoom to happen in x or y (see the links in the comments on the original question). Check the coordinate parameter in the delegate method; return the newRange to allow the zoom to happen or [space plotRangeForCoordinate:coordinate] to restore the original range and prevent zooming.
If you need to use your own gesture recognizer to detect the pinch angle, set allowPinchScaling to NO on the hosting view to disable the built-in recognizer. Add your own recognizer to the hosting view. In the handler method, decide which axis to scale (if any) and adjust the appropriate plot range accordingly. If you do it this way, you don't need a plot space delegate at all.
I am calculating the change in X and Y coordinates using UIPinchGestureRecognizer and then determining which direction the plot range should change(either X or Y). Its working fine but It is not as smooth as regular zoom, and it responds late. Can someone suggest me a better way to do this
- (void)handlePinchGesture:(UIPinchGestureRecognizer *)gestureRecognizer{
if ([gestureRecognizer state] == UIGestureRecognizerStateBegan){
CGPoint translation = [gestureRecognizer locationInView:hostView];
NSLog(#"Sender value %f %f", translation.x,translation.y );
initialX = translation.x;
initialY = translation.y;
return;
}
else if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged){
NSLog(#"inside else");
CGPoint currentTouchLocation = [gestureRecognizer locationInView:hostView];
NSLog(#"currentTouchLocation = %f and %f and ",currentTouchLocation.x, currentTouchLocation.y);
finalX = currentTouchLocation.x;
finalY = currentTouchLocation.y;
}
}
-(CPTPlotRange *)plotSpace:(CPTPlotSpace *)space willChangePlotRangeTo:(CPTPlotRange *)newRange forCoordinate:(CPTCoordinate)coordinate
{
float x = fabsf(finalX - initialX) ;
float y = fabsf(finalY - initialY);
NSLog(#"pinch x = %f pinch y = %f", x, y);
CPTPlotRange *updatedRange = nil;
if (x > y) {
switch ( coordinate ) {
case CPTCoordinateX:
NSLog(#"x is greater than y change x-range");
if (newRange.locationDouble < 0.0F ) {
CPTMutablePlotRange *mutableRange = [[newRange mutableCopy] autorelease];
mutableRange.location = CPTDecimalFromFloat(0.0);
updatedRange = mutableRange;
}
else {
updatedRange = newRange;
}
break;
case CPTCoordinateY:
NSLog(#"x is greater than y keep y range constant");
updatedRange = ((CPTXYPlotSpace *)space).yRange;
break;
}
}
if (x < y) {
switch ( coordinate ) {
case CPTCoordinateX:
NSLog(#"y is greater than x keep x-range constant");
updatedRange = ((CPTXYPlotSpace *)space).xRange;
break;
case CPTCoordinateY:
if (newRange.locationDouble < 0.0F) {
NSLog(#"y is greater than x increase y range");
CPTMutablePlotRange *mutableRange = [[newRange mutableCopy] autorelease];
// mutableRange.location = CPTDecimalFromFloat(0.0);
updatedRange = mutableRange;
}
else {
updatedRange = newRange;
}
break;
}
}
if (x == y) {
switch ( coordinate ) {
case CPTCoordinateX:
NSLog(#"y is equal to x keep x-range constant");
updatedRange = ((CPTXYPlotSpace *)space).xRange;
break;
case CPTCoordinateY:
NSLog(#"y is equal to x keep y-range constant");
//NSLog(#"%d", CPTCoordinateY);
updatedRange = ((CPTXYPlotSpace *)space).yRange;
break;
}
}
return updatedRange;
}

Zoom Layer centered on a Sprite

I am in process of developing a small game where a space-ship travels through a layer (doh!), in some situations the spaceship comes close to an enemy, and the whole layer is zoomed in on the space-ship with the zoom level being dependent on the distance between the ship and the enemy. All of this works fine.
The main question, however, is how do I keep the zoom being centered on the space-ship?
Currently I control the zooming in the GameLayer object through the update method, here is the code:
-(void) prepareLayerZoomBetweenSpaceship{
CGPoint mainSpaceShipPosition = [mainSpaceShip position];
CGPoint enemySpaceShipPosition = [enemySpaceShip position];
float distance = powf(mainSpaceShipPosition.x - enemySpaceShipPosition.x, 2) + powf(mainSpaceShipPosition.y - enemySpaceShipPosition.y,2);
distance = sqrtf(distance);
/*
Distance > 250 --> no zoom
Distance < 100 --> maximum zoom
*/
float myZoomLevel = 0.5f;
if(distance < 100){ //maximum zoom in
myZoomLevel = 1.0f;
}else if(distance > 250){
myZoomLevel = 0.5f;
}else{
myZoomLevel = 1.0f - (distance-100)*0.0033f;
}
[self zoomTo:myZoomLevel];
}
-(void) zoomTo:(float)zoom {
if(zoom > 1){
zoom = 1;
}
// Set the scale.
if(self.scale != zoom){
self.scale = zoom;
}
}
Basically my question is: How do I zoom the layer and center it exactly between the two ships? I guess this is like a pinch zoom with two fingers!
Below is some code that should get it working for you. Basically you want to:
Update your ship positions within the parentNode's coordinate system
Figure out which axis these new positions will cause the screen will be bound by.
Scale and re-position the parentNode
I added some sparse comments, but let me know if you have any more questions/issues. It might be easiest to dump this in a test project first...
ivars to put in your CCLayer:
CCNode *parentNode;
CCSprite *shipA;
CCSprite *shipB;
CGPoint destA, deltaA;
CGPoint destB, deltaB;
CGPoint halfScreenSize;
CGPoint fullScreenSize;
init stuff to put in your CCLayer:
CGSize size = [[CCDirector sharedDirector] winSize];
fullScreenSize = CGPointMake(size.width, size.height);
halfScreenSize = ccpMult(fullScreenSize, .5f);
parentNode = [CCNode node];
[self addChild:parentNode];
shipA = [CCSprite spriteWithFile:#"Icon-Small.png"]; //or whatever sprite
[parentNode addChild:shipA];
shipB = [CCSprite spriteWithFile:#"Icon-Small.png"];
[parentNode addChild:shipB];
//schedules update for every frame... might not run great.
//[self schedule:#selector(updateShips:)];
//schedules update for 25 times a second
[self schedule:#selector(updateShips:) interval:0.04f];
Zoom / Center / Ship update method:
-(void)updateShips:(ccTime)timeDelta {
//SHIP POSITION UPDATE STUFF GOES HERE
...
//1st: calc aspect ratio formed by ship positions to determine bounding axis
float shipDeltaX = fabs(shipA.position.x - shipB.position.x);
float shipDeltaY = fabs(shipA.position.y - shipB.position.y);
float newAspect = shipDeltaX / shipDeltaY;
//Then: scale based off of bounding axis
//if bound by x-axis OR deltaY is negligible
if (newAspect > (fullScreenSize.x / fullScreenSize.y) || shipDeltaY < 1.0) {
parentNode.scale = fullScreenSize.x / (shipDeltaX + shipA.contentSize.width);
}
else { //else: bound by y-axis or deltaX is negligible
parentNode.scale = fullScreenSize.y / (shipDeltaY + shipA.contentSize.height);
}
//calculate new midpoint between ships AND apply new scale to it
CGPoint scaledMidpoint = ccpMult(ccpMidpoint(shipA.position, shipB.position), parentNode.scale);
//update parent node position (move it into view of screen) to scaledMidpoint
parentNode.position = ccpSub(halfScreenSize, scaledMidpoint);
}
Also, I'm not sure how well it'll perform with a bunch of stuff going on -- but thats a separate problem!
Why don't you move the entire view, & position it so the ship is in the centre of the screen? I haven't tried it with your example, but it should be straight forward. Maybe something like this -
CGFloat x = (enemySpaceShipPosition.x - mainSpaceShipPosition.x) / 2.0 - screenCentreX;
CGFloat y = (enemySpaceShipPosition.y - mainSpaceShipPosition.y) / 2.0 - screenCentreY;
CGPoint midPointForContentOffset = CGPointMake(-x, -y);
[self setContentOffset:midPointForContentOffset];
...where you've already set up screenCentreX & Y. I haven't used UISCrollView for quite a while (been working on something in Unity so I'm forgetting all by Obj-C), & I can't remember how the contentOffset is affected by zoom level. Try it & see! (I'm assuming you're using a UIScrollView, maybe you could try that too if you're not)

Rotate a 3D Object using Touch inputs in iOS

I am working on an ios application where I need to rotate a 3d matrix (3D object) just by swiping a finger over it. the method i use for the rotation is
setRotationMatrix(float angle, float x, float y, float z, float *matrix);
However I am not sure how to use the touch's x and y location values in order to rotate the 3D matrix correctly. Here is the code that I am using
-(IBAction)handlePan:(UIPanGestureRecognizer *)recognizer {
if(recognizer.state == UIGestureRecognizerStateBegan)
{
panStartPoint = [recognizer locationInView:self];
previousPoint.x = 0;
previousPoint.y = 0;
currentPoint.x = panStartPoint.x;
currentPoint.y = panStartPoint.y;
}
else if(recognizer.state == UIGestureRecognizerStateEnded)
{
panEndPoint = [recognizer locationInView:self];
}
else if (recognizer.state == UIGestureRecognizerStateChanged)
{
previousPoint.x = currentPoint.x;
previousPoint.y = currentPoint.y;
CGPoint instanteneousPoint = [recognizer locationInView:self];
currentPoint.x = instanteneousPoint.x;
currentPoint.y = instanteneousPoint.y;
int xdifference = currentPoint.x - previousPoint.x;
int ydifference = currentPoint.y - previousPoint.y;
if((xdifference <= rotationThreshold *-1) || xdifference >= rotationThreshold) //rotationThreshold = 3;
{
if(xdifference <= rotationThreshold *-1)
{
rotationY = -1.0;
}
else
{
rotationY = 1.0;
}
if( (ydifference >= rotationThreshold *-1) && ydifference <= rotationThreshold )
{
rotationX = 0.0;
}
}
if((ydifference <= rotationThreshold *-1) || ydifference >= rotationThreshold)
{
if((ydifference <= rotationThreshold *-1))
{
rotationX = -1.0;
}
else
{
rotationX = 1.0;
}
if( (xdifference >= rotationThreshold *-1) && xdifference <= rotationThreshold )
{
rotationY = 0.0;
}
}
if(rotationX != 0.0 || rotationY != 0.0)
{
rotationDegree += 5.0f;
if(rotationDegree >= 360.0f)
{
rotationDegree = 0.0f;
}
ShaderUtils::rotatePoseMatrix(rotationDegree, rotationX, rotationY, rotationZ, &modelViewMatrix.data[0]); //rotationZ = 0;
}}}
This is providing me with some rotation of the 3D object but its not as natural as it should be. Any help will be much appreciated. Thanks.
well..i never used used UIPanGestureRecognizer so i dont know how and why doesnt it work but i used UITouch to move a 3d object (i find it to be easyer)
ok..so here is what i did (i dont have the code anymore so i cant give it to you ...sorry):
you get the first touch with touchesBegan (UITouchPhaseBegan)
then, if touchesMoved you rotate the object over x axis if touch moved on y and rotate it on y axis if touch moved on x ..and any combination of the 2 (you have to set sensitivity yourself)
also you have the option to move the object in view like this: you tap twice and then move the finger (like a laptop's track pad)
to move it on the z axis just use UIPinchGestureRecognizer
its obvious you can't move a 3d object in all 3 dimensions with a 2d surface
for more look in UITouch class reference
i may not have explained very well...but you get the basic idea
I think this should help you. It is tutorial with several ways to make it in the right way

Cocoa (not touch) collision detection of two circles

I am trying to detect the collision of two circles. The process works when a user creates circles (button click) and then mouse clicks on one of the circles to activate it. Mouse clicking anywhere outside the active circle will move the circle to the x,y of the mouse click. What I want to do is stop the movement if there is another circle within the path of the active circle.
NSPoint P = the mouse click (passed in through a notification center)
activeView = the selected circle (subclass of NSView)
My process is to get the point to move to, determine the direction of movement based on the start and end points and also the number of increments for the x start and end points, loop through the increments, use the animator method of NSView to move the view, loop through all non-active views (all the other circles) and compare their position to the current position of the active view using the formula ((x1*x2)+(x1*x2)) + (y1*y2)+(y1*y2) and comparing to the square of the radius of both circles (the circles are in a 30x30 rect with a 4 pixel stroke on the circles, so I used 26 for my radius (26*26) check.
I have a couple of issues (aside from my desire to reinvent the wheel : D - this is a learning exercise for me):
1: The movement code part actually works great. However, I'd like to get the center point of the circle on the mouse click, right now the circle is stopping so that the NSRect that contains it (30x30) x,y coordinate is at the mouse click (this is not flipped, so its lower left).
2: I am getting some collision detection but this seems to be only when the x,y of both containing rects intersect, not the circle edges.
3: Unrelated to all this, I have the NSColor for the containing rects set to clearColor and they initially start out that way but then when I move them they revert back to the default color (that gray color). Do I have to assign the clearColor each time the view is redrawn?
Thanks for the help.
hasCollision = NO;
//get point clicked value
NSValue* pVal = [[notification userInfo] objectForKey:#"dataPoint"];
//convert value to point (end point)
NSPoint p = [pVal pointValue];
//get activeView frame
NSRect avFrame = [activeView frame];
float startX = avFrame.origin.x; //x1
float startY = avFrame.origin.y; //y1
float endX = p.x; //x2
float endY = p.y; //y2
//set direction of activeView movement
if (endX > startX && endY > startY) {
//NSLog(#"endXY > startXY");
cStart = startX;
cCheck =endX;
distanceX = endX - startX;
incrementY = (endY - startY)/distanceX;
} else if (endX < startX && endY > startY) {
//NSLog(#"endX<startX, endY>startY");
cStart = endX;
cCheck =startX;
distanceX = startX - endX;
incrementY = (endY - startY)/distanceX;
} else if (endX < startX && endY < startY) {
//NSLog(#"endX<startX, endY<startY");
cStart = endX;
cCheck =startX;
distanceX = startX - endX;
incrementY = (startY - endY)/distanceX;
} else {
//NSLog(#"endX>startX, endY<startY");
cStart = startX;
cCheck =endX;
distanceX = endX - startX;
incrementY = (startY - endY)/distanceX;
}
//NSLog(#"Start:%f:%f:End%f:%f:::distance=%f:::Y Increment=%f", startX, startY, endX, endY, distanceX, incrementY);
float currentX = startX;
float currentY = startY;
for(int c=cStart; c<cCheck; c++) {
//get move coordinates
if (endX > startX && endY > startY) {
currentX++;
currentY = currentY + incrementY;
} else if (endX < startX && endY > startY) {
currentX--;
currentY = currentY + incrementY;
} else if (endX < startX && endY < startY) {
currentX--;
currentY = currentY - incrementY;
} else {
currentX++;
currentY = currentY - incrementY;
}
//move view
[[activeView animator] setFrame:NSMakeRect(currentX, currentY, avFrame.size.width, avFrame.size.height)];
//make a rect for each object
NSRect avRect = [activeView frame];
//store previous positions
prevPos = [activeView frame];
//check for collisions
for(int v=0; v<[createdViewsDict count]; v++) {
//get the id of the view in the dict
NSString* nextNum = [NSString stringWithFormat:#"circle_%i", v+1];
//init a view and assign it to the next view in the dict
NSView* thisView = [createdViewsDict objectForKey:nextNum];
//make sure this view is not our active view
if (thisView != activeView) {
NSRect tvRect = [thisView frame];
//get the xy coordinates to compare
float x1 = avRect.origin.x;
float y1 = avRect.origin.y;
float x2 = tvRect.origin.x;
float y2 = tvRect.origin.y;
float radius = 26.0;
float dx = x2-x1;
float dy = y2-y1;
float radii = radius + radius;
if ( ( dx * dx ) + ( dy * dy ) < radii * radii ) {
hasCollision = YES;
//[[activeView animator] setFrame:NSMakeRect(prevPos.origin.x, prevPos.origin.y, avFrame.size.width, avFrame.size.height)];
NSLog(#"Collision!!Moving object coords:x=%f,y=%f,:::::::::Stationary object coords:x=%f,y=%f", avRect.origin.x, avRect.origin.y, tvRect.origin.x, tvRect.origin.y);
}
/*
//check for collision
NSRect collisionRect = NSIntersectionRect(avRect, tvRect);
//move circle to previous
if ( !NSIsEmptyRect(collisionRect) ) {
hasCollision = YES;
[[activeView animator] setFrame:NSMakeRect(prevPos.origin.x, prevPos.origin.y, avFrame.size.width, avFrame.size.height)];
NSLog(#"Collision!!Moving object coords:x=%f,y=%f,:::::::::Stationary object coords:x=%f,y=%f", avRect.origin.x, avRect.origin.y, tvRect.origin.x, tvRect.origin.y);
}
*/
}
}
if(hasCollision == YES) {
[[activeView animator] setFrame:NSMakeRect(prevPos.origin.x - 20.0, prevPos.origin.y - 20.0, avFrame.size.width, avFrame.size.height)];
hasCollision = NO;
break;
}
}