Friday, October 10, 2008

A Couple More Math Snippets for 2D Graphics

Every programmer has a collection of general purpose libraries and classes that they re-use. I've got a rather extensive collection of Objective-C snippets from over the years. I periodically blow the dust off of them and use them in iPhone applications. Here's one I dug out a few weeks ago for one of the sample projects in the book.

These three functions are helpful when doing 2D graphics, either using Quartz / Core Graphics, or Open GL (but don't forget to flip the Y-axis for the latter). The first function will return the distance between two points on a 2-dimensional plane, the second will give you the absolute angle of a line formed by two points, and the third will return the angle between two lines,


#include "CGPointUtils.h"
#include <math.h>
#import "Constants.h"


CGFloat distanceBetweenPoints (CGPoint first, CGPoint second) {
CGFloat deltaX = second.x - first.x;
CGFloat deltaY = second.y - first.y;
return sqrt(deltaX*deltaX + deltaY*deltaY );
};
CGFloat angleBetweenPoints(CGPoint first, CGPoint second) {
CGFloat height = second.y - first.y;
CGFloat width = first.x - second.x;
CGFloat rads = atan(height/width);
return radiansToDegrees(rads);
//degs = degrees(atan((top - bottom)/(right - left)))
}
CGFloat angleBetweenLines(CGPoint line1Start, CGPoint line1End, CGPoint line2Start, CGPoint line2End) {

CGFloat a = line1End.x - line1Start.x;
CGFloat b = line1End.y - line1Start.y;
CGFloat c = line2End.x - line2Start.x;
CGFloat d = line2End.y - line2Start.y;

CGFloat rads = acos(((a*c) + (b*d)) / ((sqrt(a*a + b*b)) * (sqrt(c*c + d*d))));

return radiansToDegrees(rads);
}

No comments:

Post a Comment