Related
//The following game has been designed as an educational resource
//for Key Stage 1 and 2 children. Children are the future of
//civil engineering, and to inspire them to get involved in the
//industry is important for innovation. However, today the
//national curriculum is very structured, and many children
//can find themselves falling behind even at the age of 7 or 8.
//It is essential that children can be supported with material
//they find difficult, and given the resources to learn in a
//fun and engaging manner.
//One of the topics that many children struggle to grasp is
//fractions. It is necessary to prevent young children feeling
//like STEM subjects are too difficult for them, so that they
//have the opportunity and confidence to explore science and
//engineering subjects as they move into secondary education and
//careers.
//This game intends to set a precedent for teaching complex
//subjects to children in a simple, but fun and interactive
//manner. It will show them that fractions can be fun, and that
//they are capable, building confidence once they return to
//the classroom.
//The game will work by challenging the user to split a group
//of balls into three buckets depending on the fraction
//displayed on the bucket.
int number_of_balls;
float bucket_1, bucket_2, bucket_3;
int bucket_1_correct, bucket_2_correct, bucket_3_correct;
PVector basket_position, basket_dimensions;
Ball[] array_of_balls;
int linethickness;
//Random generator to give number of balls, ensuring that
//they can be divided into the number of buckets available.
void setup()
{
size(500,500);
linethickness = 4;
number_of_balls = int(random(1,11))*6;
println(number_of_balls);
bucket_1 = 1/6;
bucket_2 = 1/2;
bucket_3 = 1/3;
//Working out the correct answers
bucket_1_correct = number_of_balls*bucket_1;
bucket_2_correct = number_of_balls*bucket_2;
bucket_3_correct = number_of_balls*bucket_3;
println (bucket_1, bucket_2, bucket_3);
println (bucket_1_correct, bucket_2_correct, bucket_3_correct);
//Creating the basket
basket_position = new PVector(width/4, height/8);
basket_dimensions = new PVector(width/2, height/4);
//Creating the balls & placing inside basket
array_of_balls = new Ball[number_of_balls];
for (int index=0; index<number_of_balls; index++)
{
array_of_balls[index] = new Ball();
}
}
//Drawing the balls and basket outline
void draw()
{
background (125,95,225);
for (int index=0; index<number_of_balls; index++)
{
array_of_balls[index].Draw();
}
noFill();
stroke(180,0,0);
strokeWeight(linethickness);
rect(basket_position.x, basket_position.y, basket_dimensions.x, basket_dimensions.y);
}
void mouseDragged()
{
if ((mouseX >= (ball_position.x - radius)) && (mouseX <= (ball_position.x + radius)) && (mouseY >= (ball_position.y - radius)) && (mouseY <= (ball_position.y + radius)))
{
ball_position = new PVector (mouseX, mouseY);
}
}
//Ball_class
int radius;
Ball()
{
radius = 10;
ball_position = new PVector (random(basket_position.x + radius + linethickness, basket_position.x + basket_dimensions.x - radius - linethickness), random(basket_position.y + radius + linethickness, basket_position.y + basket_dimensions.y - radius - linethickness));
colour = color(random(255), random(255), random(255));
}
void Draw()
{
noStroke();
fill(colour);
ellipse(ball_position.x,ball_position.y,radius*2,radius*2);
}
}
Thanks in advance for your help! I am using Processing 2.2.1 which I know is very out of date, so struggling to find help.
I have a piece of code that has created a number of balls, and I would like to be able to 'drag and drop' these to a different location on the screen as part of an educational game. I've tried playing around with mousePressed() and mouseDragged() but no luck yet. Any advice would be appreciated!
There are a lot of ways to approach this, but one way I could suggest is doing something like this:
// "Ellipse" object
function Ellipse (x, y, width, height) {
// Each Ellipse object has their own x, y, width, height, and "selected" values
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.selected = false;
// You can call the draw function whenever you want something done with the object
this.draw = function() {
// Draw ellipse
ellipse(this.x, this.y, this.width, this.height);
// Check if mouse is touching the ellipse using math
// https://www.desmos.com/calculator/7a9u1bpfvt
var xDistance = this.x - mouseX;
var yDistance = this.y - mouseY;
// Ellipse formula: (x^2)/a + (y^2)/b = r^2
// Assuming r = 1 and y = 0:
// 0 + (x^2)/a = 1 Substitute values
// ((width / 2)^2)/a = 1 x = width / 2 when y = 0
// a = (width / 2)^2 Move numbers around
// a = (width^2) / 4 Evaluate
var a = Math.pow(this.width, 2) / 4;
// Assuming r = 1 and x = 0:
// 0 + (y^2)/b = 1 Substitute values
// ((height / 2)^2)/b = 1 y = height / 2 when x = 0
// b = (height / 2)^2 Move numbers around
// b = (height^2) / 4 Evaluate
var b = Math.pow(this.height, 2) / 4;
// x^2
var x2 = Math.pow(xDistance, 2);
// y^2
var y2 = Math.pow(yDistance, 2);
// Check if coordinate is inside ellipse and mouse is pressed
if(x2 / a + y2 / b < 1 && mouseIsPressed) {
this.selected = true;
}
// If mouse is released, deselect the ellipse
if(!mouseIsPressed) {
this.selected = false;
}
// If selected, then move the ellipse
if(this.selected) {
// Moves ellipse with mouse
this.x += mouseX - pmouseX;
this.y += mouseY - pmouseY;
}
};
}
// New Ellipse object
var test = new Ellipse(100, 100, 90, 60);
draw = function() {
background(255);
// Do everything associated with that object
test.draw();
};
The math is a bit funky, and I might not be using the right version of Processing, but hopefully you found this at least slightly helpful :)
I'm kind of confused about what language you're using. Processing is a wrapper for Java, not JavaScript. Processing.js went up to version 1.6.6 and then was succeeded by p5.js. I'm going to assume you're using p5.js.
I don't know if this is a new thing in p5.js, but for easy, but not very user-friendly click-and-drag functionality I like to use the built-in variable mouseIsPressed.
If the ellipse coordinates are stored in an array of vectors, you might do something like this:
let balls = [];
let radius = 10;
function setup() {
createCanvas(400, 400);
for (let i = 0; i < 10; i++) {
balls.push(createVector(random(width), random(height)));
}
}
function draw() {
background(220);
for (let i = 0; i < balls.length && mouseIsPressed; i++) {
if (dist(mouseX, mouseY, balls[i].x, balls[i].y) < radius) {
balls[i] = createVector(mouseX, mouseY);
i = balls.length;
}
}
for (let i = 0; i < balls.length; i++) {
ellipse(balls[i].x, balls[i].y,
2 * radius, 2 * radius
);
}
}
This is the quickest way I could think of, but there are better ways to do it (at least, there are in p5.js). You could make a Ball class which has numbers for x, y, and radius, as well as a boolean for whether it's being dragged. In that class, you could make a method mouseOn() which detects whether the cursor is within the radius (if it's not a circle, you can use two radii: sq((this.x - mouseX)/r1) + sq((this.y - mouseY)/r2) < 1).
When the mouse is pressed, you can cycle through all the balls in the array of balls, and test each of them with mouseOn(), and set their drag boolean to true. When the mouse is released, you can set all of their drag booleans to false. Here's what it looks like in the current version of p5.js:
function mousePressed() {
for (let i = 0; i < balls.length; i++) {
balls[i].drag = balls[i].mouseOn();
if (balls[i].drag) {
i = balls.length;
}
}
}
function mouseReleased() {
for (let i = 0; i < balls.length; i++) {
balls[i].drag = false;
}
}
I hope this helps.
The way your code is right now doesn't work in the current version of Processing either, but it's a pretty quick fix. I'm going to show you a way to fix that, and hopefully it'll work in the earlier version.
Here's where I think the problem is: when you use mouseDragged(), you try to change ball_position, but you don't specify which ball's position. Here's one solution, changing the mouseDragged() block and the Ball class:
void mouseDragged() {
for (int i = 0; i < array_of_balls.length; i++) {
if ((mouseX > (array_of_balls[i].ball_position.x - array_of_balls[i].radius)) &&
(mouseX < (array_of_balls[i].ball_position.x + array_of_balls[i].radius)) &&
(mouseY > (array_of_balls[i].ball_position.y - array_of_balls[i].radius)) &&
(mouseY < (array_of_balls[i].ball_position.y + array_of_balls[i].radius))
) {
array_of_balls[i].ball_position = new PVector (mouseX, mouseY);
i = array_of_balls.length;
}
}
}
//Ball_class
class Ball {
int radius;
PVector ball_position;
color colour;
Ball() {
radius = 10;
ball_position = new PVector (random(basket_position.x + radius + linethickness, basket_position.x + basket_dimensions.x - radius - linethickness), random(basket_position.y + radius + linethickness, basket_position.y + basket_dimensions.y - radius - linethickness));
colour = color(random(255), random(255), random(255));
}
void Draw() {
noStroke();
fill(colour);
ellipse(ball_position.x, ball_position.y, radius*2, radius*2);
}
}
P.S. Since you're using a language based in Java, you should probably adhere to the finnicky parts of the language:
data types are very strict in Java. Avoid assigning anything that could possibly be a float to a variable that is declared as an int. For example, in your setup() block, you say bucket_1_correct = number_of_balls*bucket_1;. This might seem like not an issue, since number_of_balls*bucket_1 is always going to be a whole number. But since the computer rounds when saving bucket_1 = 1/6, multiplying it by 6 doesn't necessarily give a whole number. In this case, you can just use round(): bucket_1_correct = round(number_of_balls*bucket_1);
Regarding data types, you should always declare your variables with their data type. It's a little hard for me to tell, but it looks to me like you never declared ball_position or colour in your Ball class, and you never opened up the class with the typical class Ball {. This might have been a copy/paste error, though.
i am making an navigation based application. In this application i am drawing a route from points selected by the user. I have requirement of recalculating route if user is not following the route.
for Calculating the route i have used Google direction API. and for drawing the route i have used this code
- (void) drawRoute:(NSArray *) path
{
NSInteger numberOfSteps = path.count;
[self.objMapView removeOverlays: self.objMapView.overlays];
CLLocationCoordinate2D coordinates[numberOfSteps];
for (NSInteger index = 0; index < numberOfSteps; index++)
{
CLLocation *location = [path objectAtIndex:index];
CLLocationCoordinate2D coordinate = location.coordinate;
coordinates[index] = coordinate;
}
for( id <MKOverlay> ovr in [self.objMapView overlays])
{
MKPolylineView *polylineView = [[MKPolylineView alloc] initWithPolyline:ovr];
if (polylineView.tag == 22)
{
[self.objMapView removeOverlay:ovr];
}
[polylineView release];
}
MKPolyline *polyLine = [MKPolyline polylineWithCoordinates:coordinates count:numberOfSteps];
[self.objMapView addOverlay:polyLine];
}
Till now every thing is okey.
Now, i want a notification if user is out of route (more than 100 meters).and i can get the notification also
PROBLEM:~ if road is straight (more than 100mt) then i cant get points on the road. To explain the problem i have attached the image...
In this image suppose black line is my path (polyline) and red circles are the points i got form google apis. but in the straight path shown as blue circle i cant get points to compare and in this path recalculation function is called.
Can any one tell me the solution from which i can get all points of route even if it is a straight road.
I know this is an old thread, but recently ran into the same problem and found an OK solution.
The concept is that you don't calculate the distance to EACH line segment but only to the TWO segments connected to the closest point.
calculate the distance of your current location to all the points in the
MKPolyline and take the minimum from that. (There's probably some nice way to optimize this. Like not iterating through all the points on every location update, but don't have time to dig in to that now).
You now know the distance to the closest polyline-point. However that point might still be far away while the polyline itself (connecting this point and the previous or the next point) might be closer. So, calculate the distance between your current location and these two line-segments and you have the closest distance.
Now, this is not waterproof. While it minimizes the nr of api calls, on some occasions (If you have crazy bends and curves in the MKPolyline) it might call the api while not needed, but hey, then the same line will be drawn again, no damage done. In my tests it worked fine and you can also adjust the accuracy. I've set it to 200m (0.2km) in the code below.
//Get Coordinates of points in MKPolyline
NSUInteger pointCount = routeLineGuidanceTurn.pointCount;
CLLocationCoordinate2D *routeCoordinates = malloc(pointCount * sizeof(CLLocationCoordinate2D));
[routeLineGuidanceTurn getCoordinates:routeCoordinates
range:NSMakeRange(0, pointCount)];
NSLog(#"route pointCount = %d", pointCount);
//Determine Minimum Distance and GuidancePoints from
double MinDistanceFromGuidanceInKM = 1000;
CLLocationCoordinate2D prevPoint;
CLLocationCoordinate2D pointWithMinDistance;
CLLocationCoordinate2D nextPoint;
for (int c=0; c < pointCount; c++)
{
double newDistanceInKM = [self distanceBetweentwoPoints:Currentcordinate.latitude longitude:Currentcordinate.longitude Old:routeCoordinates[c].latitude longitude:routeCoordinates[c].longitude];
if (newDistanceInKM < MinDistanceFromGuidanceInKM) {
MinDistanceFromGuidanceInKM = newDistanceInKM;
prevPoint = routeCoordinates[MAX(c-1,0)];
pointWithMinDistance = routeCoordinates[c];
nextPoint = routeCoordinates[MIN(c+1,pointCount-1)];
}
}
free(routeCoordinates);
NSLog(#"MinDistanceBefore: %f",MinDistanceFromGuidanceInKM);
//If minimum distance > 200m we might have to recalc GuidanceLine.
//To be sure we take the two linesegments connected to the point with the shortest distance and calculate the distance from our current position to that linedistance.
if (MinDistanceFromGuidanceInKM > 0.2) {
MinDistanceFromGuidanceInKM = MIN(MIN([self lineSegmentDistanceFromOrigin:Currentcordinate onLineSegmentPointA:prevPoint pointB:pointWithMinDistance], [self lineSegmentDistanceFromOrigin:Currentcordinate onLineSegmentPointA:pointWithMinDistance pointB:nextPoint]),MinDistanceFromGuidanceInKM);
if (MinDistanceFromGuidanceInKM > 0.2) {
// Call the API and redraw the polyline.
}
}
Here's the fun that calculate sthe distance between two points. I know there is a built in function for it, but had it in my code already.
-(double)distanceBetweentwoPoints:(double)Nlat longitude:(double)Nlon Old:(double)Olat longitude:(double)Olon {
//NSLog(#"distanceBetweentwoPoints");
double Math=3.14159265;
double radlat1 = Math* Nlat/180;
double radlat2 = Math * Olat/180;
double theta = Nlon-Olon;
double radtheta = Math * theta/180;
double dist = sin(radlat1) * sin(radlat2) + cos(radlat1) * cos(radlat2) * cos(radtheta);
if (dist>1) {dist=1;} else if (dist<-1) {dist=-1;}
dist = acos(dist);
dist = dist * 180/Math;
dist = dist * 60 * 1.1515;
return dist * 1.609344;
}
And here's the bit that calculates the distance between a point and a line segment between two other points. I got this from here: https://stackoverflow.com/a/28028023/3139134 Modified it a bit to work with CLLocationCoordinate2D and return the distance.
- (CGFloat)lineSegmentDistanceFromOrigin:(CLLocationCoordinate2D)origin onLineSegmentPointA:(CLLocationCoordinate2D)pointA pointB:(CLLocationCoordinate2D)pointB {
CGPoint dAP = CGPointMake(origin.longitude - pointA.longitude, origin.latitude - pointA.latitude);
CGPoint dAB = CGPointMake(pointB.longitude - pointA.longitude, pointB.latitude - pointA.latitude);
CGFloat dot = dAP.x * dAB.x + dAP.y * dAB.y;
CGFloat squareLength = dAB.x * dAB.x + dAB.y * dAB.y;
CGFloat param = dot / squareLength;
CGPoint nearestPoint;
if (param < 0 || (pointA.longitude == pointB.longitude && pointA.latitude == pointB.latitude)) {
nearestPoint.x = pointA.longitude;
nearestPoint.y = pointA.latitude;
} else if (param > 1) {
nearestPoint.x = pointB.longitude;
nearestPoint.y = pointB.latitude;
} else {
nearestPoint.x = pointA.longitude + param * dAB.x;
nearestPoint.y = pointA.latitude + param * dAB.y;
}
CGFloat dx = origin.longitude - nearestPoint.x;
CGFloat dy = origin.latitude - nearestPoint.y;
return sqrtf(dx * dx + dy * dy) * 100;
}
For each pair of points in each step, you can calculate the distance between them using the Pythagorean Theorem:
distance = sqrt( pow((point1.x - point2.x), 2) + pow((point1.y - point2.y), 2) )
Then, if the distance is greater than 100m, add intermediary points along the line segment.
I'm trying to develop an application that use the GPS and Compass of the iPhone in order to point some sort of pointer to a specific location (like the compass always point to the North). The location is fixed and I always need the pointer to point to that specific location no matter where the user is located. I have the Lat/Long coordinates of this location but not sure how can I point to that location using the Compass and the GPS... just like http://www.youtube.com/watch?v=iC0Xn8hY80w this link 1:20'
I write some code, however, it can't rotate right direction.
-(float) angleToRadians:(double) a {
return ((a/180)*M_PI);
}
-(void)updateArrow {
double alon=[longi doubleValue];//source
double alat=[lati doubleValue];//source
double blon=[pointlongi doubleValue];//destination
double blat=[pointlati doubleValue];//destination
float fLat = [self angleToRadians:alat];
float fLng = [self angleToRadians:alon];
float tLat = [self angleToRadians:blat];
float tLng = [self angleToRadians:blon];
float temp = atan2(sin(tLng-fLng)*cos(tLat),
cos(fLat)*sin(tLat)-sin(fLat)*cos(tLat)*cos(tLng-fLng));
double temp2= previousHeading;
double temp1=temp-[self angleToRadians:temp2];
/*I using this,but it can't rotate by :point even i change the coordinate
in CGPointMake */
Compass2.layer.anchorPoint=CGPointMake(0, 0.5);
[Compass2 setTransform:CGAffineTransformMakeRotation(temp1)];
/* Compass2 is a UIImageView like below picture I want to rotate it around
: point in image
^
|
|
|
:
|
*/
There is a standard "heading" or "bearing" equation that you can use - if you are at lat1,lon1, and the point you are interested in is at lat2,lon2, then the equation is:
heading = atan2( sin(lon2-lon1)*cos(lat2), cos(lat1)*sin(lat2) - sin(lat1)*cos(lat2)*cos(lon2-lon1))
This gives you a bearing in radians, which you can convert to degrees by multiplying by 180/π. The value is then between -180 and 180 degrees, so to get a standard compass bearing add 360 to any negative answers.
atan2 is a standard function related to arctan, that does the right thing for the four possible quadrants that your destination point could be in compared to where you are.
1) Get your current location (from the GPS)
2) Get the differences in latitude and longitude
3) use the atan2 method to get the angle
i.e. (WARNING: untested code)
CLLocation *targetLocation = [CLLocation alloc] initWithLatitude:1 longitude:2];
CLLocation *sourceLocation = <get from GPS>
double dx = [targetLocation coordinate].latitude - [sourceLocation coordinate].latitude;
double dy = [targetLocation coordinate].longitude - [sourceLocation coordinate].longitude;
double angle = atan2(dx, dy);
You might have to tweak that to get it to compile but the idea is there!
I did this some time ago, here are two different implementations. The first is similar to your approach, the second is without the trig math. The first is what I used in my app, but the second seemed to work as well, though doesn't appear to be as clean. You will need to also remember to offset this bearing based on north in your UI.
- (double) toRadian: (double) val
{
return val * (M_PI / 180);
}
// Convert to degrees from radians
- (double) toDegrees: (double) val
{
return val * 180 / M_PI;
}
// convert from a radian to a 360 degree format.
- (double) toBearing: (double) val
{
return ( (int)([self toDegrees: val]) + 360 ) % 360; // use mod to get the degrees
}
// Calculate the bearing based off of the passed coordinates and destination.
//
- (double) calcBearingWithLatitude:(CLLocationDegrees)latSource
latitude:(CLLocationDegrees)latDest
longitude:(CLLocationDegrees)lonSrc
longitude:(CLLocationDegrees)lonDest
{
double lat1 = [self toRadian:latSource];
double lat2 = [self toRadian:latDest];
double dLon = [self toRadian:(lonDest - lonSrc)];
double y = sin(dLon) * cos(lat2);
double x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon);
return [self toBearing:atan2(y, x)];
}
And the second.
// got this code from some forums and modified it, thanks for posting it coullis! Mostly here for reference on how to do this without sin and cos.
- (CLLocationDegrees) altCalcBearingWithLatitude:(CLLocationDegrees)latSource
latitude:(CLLocationDegrees)latDest
longitude:(CLLocationDegrees)lonSrc
longitude:(CLLocationDegrees)lonDest
{
CLLocationDegrees result;
// First You calculate Delta distances.
float dx = lonSrc - latSource;
float dy = lonDest - latDest;
// If x part is 0 we could get into division by zero problems, but in that case result can only be 90 or 270:
if (dx==0)
{
if (dy > 0)
result = 90;
else
result = 270;
}
else
{
result = [self toDegrees: atan(dy/dx)];
}
// This is only valid for two quadrants (for right side of the coordinate system) so modify result if necessary...
if (dx < 0)
result = result + 180;
// looks better if all numbers are positive (0 to 360 range)
if (result < 0)
result = result + 360;
// return our result.
return result;
}
Use this. You will have to subtract out your actual compass heading from the result of getHeadingForDirection to determine the proper relative heading. Return value is heading in radians.
-(float) angleToRadians:(float) a {
return ((a/180)*M_PI);
}
- (float) getHeadingForDirectionFromCoordinate:(CLLocationCoordinate2D)fromLoc toCoordinate:(CLLocationCoordinate2D)toLoc
{
float fLat = [self angleToRadians:fromLoc.latitude];
float fLng = [self angleToRadians:fromLoc.longitude];
float tLat = [self angleToRadians:toLoc.latitude];
float tLng = [self angleToRadians:toLoc.longitude];
return atan2(sin(tLng-fLng)*cos(tLat), cos(fLat)*sin(tLat)-sin(fLat)*cos(tLat)*cos(tLng-fLng));
}
I'm trying to develop an application that use the GPS and Compass of the iPhone in order to point some sort of pointer to a specific location (like the compass always point to the North). The location is fixed and I always need the pointer to point to that specific location no matter where the user is located. I have the Lat/Long coordinates of this location but not sure how can I point to that location using the Compass and the GPS... just like http://www.youtube.com/watch?v=iC0Xn8hY80w this link 1:20'
I write some code, however, it can't rotate right direction.
-(float) angleToRadians:(double) a {
return ((a/180)*M_PI);
}
-(void)updateArrow {
double alon=[longi doubleValue];//source
double alat=[lati doubleValue];//source
double blon=[pointlongi doubleValue];//destination
double blat=[pointlati doubleValue];//destination
float fLat = [self angleToRadians:alat];
float fLng = [self angleToRadians:alon];
float tLat = [self angleToRadians:blat];
float tLng = [self angleToRadians:blon];
float temp = atan2(sin(tLng-fLng)*cos(tLat),
cos(fLat)*sin(tLat)-sin(fLat)*cos(tLat)*cos(tLng-fLng));
double temp2= previousHeading;
double temp1=temp-[self angleToRadians:temp2];
/*I using this,but it can't rotate by :point even i change the coordinate
in CGPointMake */
Compass2.layer.anchorPoint=CGPointMake(0, 0.5);
[Compass2 setTransform:CGAffineTransformMakeRotation(temp1)];
/* Compass2 is a UIImageView like below picture I want to rotate it around
: point in image
^
|
|
|
:
|
*/
There is a standard "heading" or "bearing" equation that you can use - if you are at lat1,lon1, and the point you are interested in is at lat2,lon2, then the equation is:
heading = atan2( sin(lon2-lon1)*cos(lat2), cos(lat1)*sin(lat2) - sin(lat1)*cos(lat2)*cos(lon2-lon1))
This gives you a bearing in radians, which you can convert to degrees by multiplying by 180/π. The value is then between -180 and 180 degrees, so to get a standard compass bearing add 360 to any negative answers.
atan2 is a standard function related to arctan, that does the right thing for the four possible quadrants that your destination point could be in compared to where you are.
1) Get your current location (from the GPS)
2) Get the differences in latitude and longitude
3) use the atan2 method to get the angle
i.e. (WARNING: untested code)
CLLocation *targetLocation = [CLLocation alloc] initWithLatitude:1 longitude:2];
CLLocation *sourceLocation = <get from GPS>
double dx = [targetLocation coordinate].latitude - [sourceLocation coordinate].latitude;
double dy = [targetLocation coordinate].longitude - [sourceLocation coordinate].longitude;
double angle = atan2(dx, dy);
You might have to tweak that to get it to compile but the idea is there!
I did this some time ago, here are two different implementations. The first is similar to your approach, the second is without the trig math. The first is what I used in my app, but the second seemed to work as well, though doesn't appear to be as clean. You will need to also remember to offset this bearing based on north in your UI.
- (double) toRadian: (double) val
{
return val * (M_PI / 180);
}
// Convert to degrees from radians
- (double) toDegrees: (double) val
{
return val * 180 / M_PI;
}
// convert from a radian to a 360 degree format.
- (double) toBearing: (double) val
{
return ( (int)([self toDegrees: val]) + 360 ) % 360; // use mod to get the degrees
}
// Calculate the bearing based off of the passed coordinates and destination.
//
- (double) calcBearingWithLatitude:(CLLocationDegrees)latSource
latitude:(CLLocationDegrees)latDest
longitude:(CLLocationDegrees)lonSrc
longitude:(CLLocationDegrees)lonDest
{
double lat1 = [self toRadian:latSource];
double lat2 = [self toRadian:latDest];
double dLon = [self toRadian:(lonDest - lonSrc)];
double y = sin(dLon) * cos(lat2);
double x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon);
return [self toBearing:atan2(y, x)];
}
And the second.
// got this code from some forums and modified it, thanks for posting it coullis! Mostly here for reference on how to do this without sin and cos.
- (CLLocationDegrees) altCalcBearingWithLatitude:(CLLocationDegrees)latSource
latitude:(CLLocationDegrees)latDest
longitude:(CLLocationDegrees)lonSrc
longitude:(CLLocationDegrees)lonDest
{
CLLocationDegrees result;
// First You calculate Delta distances.
float dx = lonSrc - latSource;
float dy = lonDest - latDest;
// If x part is 0 we could get into division by zero problems, but in that case result can only be 90 or 270:
if (dx==0)
{
if (dy > 0)
result = 90;
else
result = 270;
}
else
{
result = [self toDegrees: atan(dy/dx)];
}
// This is only valid for two quadrants (for right side of the coordinate system) so modify result if necessary...
if (dx < 0)
result = result + 180;
// looks better if all numbers are positive (0 to 360 range)
if (result < 0)
result = result + 360;
// return our result.
return result;
}
Use this. You will have to subtract out your actual compass heading from the result of getHeadingForDirection to determine the proper relative heading. Return value is heading in radians.
-(float) angleToRadians:(float) a {
return ((a/180)*M_PI);
}
- (float) getHeadingForDirectionFromCoordinate:(CLLocationCoordinate2D)fromLoc toCoordinate:(CLLocationCoordinate2D)toLoc
{
float fLat = [self angleToRadians:fromLoc.latitude];
float fLng = [self angleToRadians:fromLoc.longitude];
float tLat = [self angleToRadians:toLoc.latitude];
float tLng = [self angleToRadians:toLoc.longitude];
return atan2(sin(tLng-fLng)*cos(tLat), cos(fLat)*sin(tLat)-sin(fLat)*cos(tLat)*cos(tLng-fLng));
}
I've tried several ways of measuring the steps a user makes with an iPhone by reading the accelerometer, but none have been very accurate. The most accurate implementation I've used is the following:
float xx = acceleration.x;
float yy = acceleration.y;
float zz = acceleration.z;
float dot = (mOldAccX * xx) + (mOldAccY * yy) + (mOldAccZ * zz);
float a = ABS(sqrt(mOldAccX * mOldAccX + mOldAccY * mOldAccY + mOldAccZ * mOldAccZ));
float b = ABS(sqrt(xx * xx + yy * yy + zz * zz));
dot /= (a * b);
if (dot <= 0.994 && dot > 0.90) // bounce
{
if (!isChange)
{
isChange = YES;
mNumberOfSteps += 1;
} else {
isChange = NO;
}
}
mOldAccX = xx;
mOldAccY = yy;
mOldAccZ = zz;
}
However, this only catches 80% of the user's steps. How can I improve the accuracy of my pedometer?
Here is some more precise answer to detect each step. But yes in my case I am getting + or - 1 step with every 25 steps. So I hope this might be helpful to you. :)
if (dot <= 0.90) {
if (!isSleeping) {
isSleeping = YES;
[self performSelector:#selector(wakeUp) withObject:nil afterDelay:0.3];
numSteps += 1;
self.stepsCount.text = [NSString stringWithFormat:#"%d", numSteps];
}
}
- (void)wakeUp {
isSleeping = NO;
}
ok, I'm assuming this code is within the addAcceleration function...
-(void)addAcceleration:(UIAcceleration*)accel
So, you could increase your sampling rate to get a finer granularity of detection. So for example, if you are currently taking 30 samples per second, you could increase it to 40, 50, or 60 etc... Then decide if you need to count a number of samples that fall within your bounce and consider that a single step. It sounds like you are not counting some steps due to missing some of the bounces.
Also, what is the purpose of toggling isChange? Shouldn't you use a counter with a reset after x number of counts? If you are within your bounce...
if (dot <= 0.994 && dot > 0.90) // bounce
you would have to hit this sweet spot 2 times, but the way you have set this up, it may not be two consecutive samples in a row, it may be a first sample and a 5th sample, or a 2nd sample and an 11th sample. That is where you are loosing step counts.
Keep in mind that not everyone makes the same big steps. So the dot calculation should be adjusted according to someone's length, step size.
You should adjust the bounce threshold accordingly. Try to make the program learn about it's passenger.