I am having trouble plotting a new CGPoint when given an origin, distance and angle. The task is pretty simple: I have a line with three edit handles attached to it - one on each end and one in the center. When the the end handles are dragged, the line is moved relative to the handle being dragged. That functionality is working properly. When the center handle is dragged, the two endpoint handles should maintain their relationship to one another as shown in the image below. So when dragging the center handle the two other handles should move with it.
Here is my current code to plot the points:
func pointFromPoint(origin:CGPoint, distance:Double, degrees:Double) -> CGPoint {
var endPoint = CGPoint()
endPoint.x = CGFloat(distance * cos(degrees) + Double(origin.x))
endPoint.y = CGFloat(distance * sin(degrees) + Double(origin.y))
return endPoint
}
When using this function, the new CGPoint locations seems to fall in random locations. Can anyone spot anything wrong in my math? Thanks!
Most trigonometry functions need radians, not degrees.
Also, as #Putz1103 pointed out, you can probably use the delta x and delta y of the UITouch of the movement instead of calculating the new position of the ends based on the center point's movement.
Related
I have a game where I'm moving square Blocks on a top layer overtop circles underneath, which are non-moveable. So when the dragging of a block ceases, I want to run a check or an if statement to see if the block I'm moving (myBlocks[objectDragging]) is within x amount of pixels of the center of my circle (myCircles[objectDragging]). objectDragging is just getting the tag of the image clicked. The matchable circle will have the same tag. Everything is working fine, I just cannot figure out how to check if the block I'm dropping (it's center point) is within so many pixels of the circles center point.
Some of what I'm working with:
var myBlocks = [UIImageView]()
var myCircles = [UIImageView]()
let objectDragging = recognizer.view?.tag
if myBlocks[objectDragging!].center.x == myCircles[objectDragging!].center.x {
...
} //this checks for an exact match of center.x where-as I want to check
//if the center.x for myBlocks[objectDragging!] is <= we'll say,
//25, pixels of the myCircles[objectDragging!].center.x
Discussion here to find distance between two CGPoints:
How to find the distance between two CG points?
per Lucius (answer 2)
You can use the hypot() or hypotf() function to calculate the
hypotenuse. Given two points p1 and p2:
CGFloat distance = hypotf(p1.x - p2.x, p1.y - p2.y);
sub in your myBlocks.center and myCircles.center for p1 and p2 and then
if distance < 25 {
...
}
I essentially want the "sprites" to collide when they stick together. However, I don't want the "joint" to be rigid; I essentially want the sprites to be able to move around as long as they are in contact with each other. Imagine two circles connected, and you can move one circle around the other, as long as it remains in contact.
I found this question: How to make one body stick to another moving object in SpriteKit and a lot of other resources that explain how to make sprites stick upon collision, but they all use SKJoints, which are rigid are not really flexible.
I guess another way to phrase it would be to say that I want the sprites to stick, but I want them to be able to "slide" on each other.
Well, I can think of one workaround, but this wouldn't work with non-normal polygons.
Sticking (pun unintended) with your circles example, what if you lock the position of the circle?
let circle1 = center circle
let circle2 = movable circle
Knowing the width of both circles, you can place in the update function that the position should be exactly the distance of:
((circle1.frame.width / 2) + (circle2.frame.width / 2))
If you're up to it, here's some code to help you on your way.
override func update(currentTime: CFTimeInterval) {
{
let distance = hypotf(Float(circle1.position.x - circle2.position.x), Float(circle1.position.y - circle2.position.y))
//calculate circle distances from each other
let radius = ((circle1.frame.width / 2) + (circle2.frame.width / 2))
//distance of circle positions
if distance != radius
{
//if distance is less or more than radius
let pointA = circle1.position
let pointB = circle2.position
let pointC = CGPointMake(pointB.x + 2, pointB.y)
let angle_ab = atan2(pointA.y - pointB.y, pointA.x - pointB.x)
let angle_cb = atan2(pointC.y - pointB.y, pointC.x - pointB.x)
let angle_abc = angle_ab - angle_cb
//get angle of circles from each other using atan2
let vectorx = cos(angle_abc)
let vectory = sin(angle_abc)
//convert angle into vectors
let x = circle1.position.x + radius * vectorx
let y = circle1.position.y + radius * vectory
//get new coordinates from vector, radius and center circle position
circle2.position = CGPointMake(x, y)
//set new position
}
}
Well you need to write code to make sure the movable circle, is well movable.
But, this should work.
I haven't tested this yet though, and I haven't even learned geometry let alone trig in school yet.
If I'm reading your question as you intended it, you can still use joints- just create actions with Inverse Kinematic constraints that allow rotation and translation around the contacting circles' joint.
https://developer.apple.com/library/prerelease/ios/documentation/SpriteKit/Reference/SKAction_Ref/index.html#//apple_ref/doc/uid/TP40013017-CH1-SW72
I am trying to calculate the coordinates along a circle corresponding to the tap location. The coordinates should be on the border of the circle nearest to the tap location (e.g. the border that is less distant from the radius). To facilitate this I am detecting only taps that are distant by 80% of the radius from the circle center.
Input:
P (GPPoint) - center of the circle
P1 (GPPoint) current position of an image displayed
r (float) radius of circle
P3 (CGPoint) user tap coordinate
Desired output:
P2 (CGPoint) - new coordinates for the image corresponding to P3 but along the circle. Sorry for the bad explanation, I try to explain it in other words: once the user taps on the screen I would like to move the image in P2. P2 should be derived by moving P2 to the border of the circle. It should be possible to do so by using the radius information.
The idea is to create from P3 coordinates a new coordinate called P2 as described above - the key is that P2 distance from the centre should correspond exactly to the radius and the ANGLE should be the same as tapPoint.
Would anyome be able to suggest a formula to calculate the corresponding coordinate given a tap? I simply need to calculate P3 using the input I have.
Code so far:
-(void)tapInImageView:(UITapGestureRecognizer *)tap
{
CGPoint tapPoint = [tap locationInView:tap.view];
if ([self isInOuternCircle:tapPoint]) {
// then create from tapPoint coordinates a new coordinate P2 as described above - but have no idea how.. the key is that P2 distance from the centre should correspond exactly to the radius and the ANGLE should be the same as tapPoint.
}
}
-(BOOL)isInOuternCircle:(CGPoint)point
{
double distanceToCenter = sqrt((point.x - _timerView.center.x)*(point.x - _timerView.center.x) + (point.y - _timerView.center.y)*(point.y - _timerView.center.y));
if (distanceToCenter < _innerCircleRadius) {
return false;
}
return true;
}
I've done this once before, but the math usually depends on how you've set up your coordinate system, so I'll just outline what I did. You'll need a bit of geometry, and a few formulae to determine the new coordinate along the circle.
Calculate the formula of a line passing through the center (P) and your tap point (P3) using this: http://en.wikipedia.org/wiki/Linear_equation#Two-point_form
Determine the equation for your circle: http://en.wikipedia.org/wiki/Circle#Equations
Using the above two equations, you'll have a system of a linear and a quadratic equation: http://www.mathsisfun.com/algebra/systems-linear-quadratic-equations.html
Once you have the equation above, you need to solve it. The result will yield two possible points (the line will intersect the circle in two places), and the point you are looking for is the point closer the tap point. In this case, just compare the distances to P3 between the two solutions, and the shorter distance will show your required solution - P2.
Basically i have a list of POI's (name,lat,long) and i want to draw them on the UIView, relative to my current lat/long. I'm looking for some best practice for mapping these POI (lat/long) to a UIView.
I don't want to use MKMapView (no need for displaying map-data).
I was reading:
http://developer.apple.com/library/ios/#documentation/general/conceptual/Devpedia-CocoaApp/CoordinateSystem.html
But I'm clueless how i get from a CLLocation to a (x,y) on my UIView. I only want to draw those POI's around my current location. So, for example if my screen would represent a 20 by 30 KM region, how do i map my POI's to their corresponding (x,y) coordinates?
Thanks.
What you're doing is a little strange, but you can convert latitude/longitude to a CGPoint-like struct called an MKMapPoint. An MKMapPoint has an x and y value which correspond to points on a map. Imagine if you laid out a flat map of the world, and 0,0 was the top left. MKMapPoint is a point on that map using that coordinate system.
Use the function MKMapPointForCoordinate() to convert a CLLocationCoordinate2D to an MKMapPoint
MKMapPoint myMapPoint = MKMapPointForCoordinate(myLocationCoordinate);
When you get the list of points, you'll have to do something like finding the max and min x and y values, then fitting all the points into your view using those values, otherwise you'll end up with a load of very close points in one place in your view.
My guess is that, for a 20KM by 30KM region, you can consider the earth to be flat and there fore linearly extrapolate the coordinates. I am sure you can google and find out as to how much distance is a difference in 0.00001 in latitude and longitude.
So if you have 20Km to be represented on X axis, and your current location is 30.1234567 in latitude, and 0.0000001 is 1 km then you can put your coordinate in the center of the screen and 30.1234557 as the left most X coordinate and so on.
I am not trying to provide an answer here, but just trying to think out loud, because I wanted to do some thing similar as well and did it as an Internet based app (without display though), where given two coordinates, I had to find the distance between them.
There are many (many) different approaches to modelling the planet and translating 3D coordinates onto a 2D surface, and the errors introduced by the various methods vary depending on what part of the globe you are. This question seems to cover most of what you are after though:
Converting Longitude & Latitude to X Y on a map with Calibration points
I think its best way (correctly work for Mercator projection map):
extension UIView
{
func addLocation(coordinate: CLLocationCoordinate2D)
{
// max MKMapPoint values
let maxY = Double(267995781)
let maxX = Double(268435456)
let mapPoint = MKMapPointForCoordinate(coordinate)
let normalizatePointX = CGFloat(mapPoint.x / maxX)
let normalizatePointY = CGFloat(mapPoint.y / maxY)
let pointView = UIView(frame: CGRectMake(0, 0, 5, 5))
pointView.center = CGPointMake(normalizatePointX * frame.width, normalizatePointY * frame.height)
pointView.backgroundColor = UIColor.blueColor()
addSubview(pointView)
}
}
My simple project for adding coordinate on UIView: https://github.com/Glechik/MapCoordinateDrawer
From what I have read, in Box2d, you get the angle of a revolute joint with the GetJointAngle function, but when trying to set the angle the member m_referenceAngle is protected. Can the angle not be programmatically set?
I found that I can apply the angle from one joint to another body as:
float FirstAngle = firstArmJoint->GetJointAngle();
secondArmBody->SetTransform(b2Vec2((750.0/PTM_RATIO),(520.0f+100)/PTM_RATIO),hourAngle);
I put this in ccTouchesMoved so that when the user drags the first object (from which FirstAngle is retrieved) the second object (secondArmBody) is also moved.
What happens is that the second body rotates at the top of the image and not at the anchor point.
Any ideas?
SetTransform() can be used to set the position and rotation of a body. This happens completely independently of any joints on the body. For example, if you want to make sure a body is perfectly upright at a given moment, you can call
body->SetTransForm(body->GetPosition(), 0);
passing 0 as the angle value (upright). I've never tried this for a body with a joint on it, but I doubt it would work properly.
When I ran into the problem of having to make a revolutejoint point at a certain angle, I solved it by enabling motor on the joint and adjusting the motor speed until the angle matched the one I wanted. This simulates realistic motion of the joint. Example:
Creating the joint
b2RevoluteJointDef armJointDef;
armJointDef.Initialize(body1, body2,
b2Vec2(body1->GetPosition().x,
((body1->GetPosition().y/PTM_RATIO));
armJointDef.enableMotor = true;
armJointDef.enableLimit = true;
armJointDef.motorSpeed = 0.0f;
armJointDef.maxMotorTorque = 10000.0f;
armJointDef.lowerAngle = CC_DEGREES_TO_RADIANS(lowerArmAngle);
armJointDef.upperAngle = CC_DEGREES_TO_RADIANS(upperArmAngle);
_world->CreateJoint(&armJointDef);
Pointing the joint
float targetAngle = SOME_ANGLE;
b2JointEdge *j = body->GetJointList();
b2RevoluteJoint *r = (b2RevoluteJoint *)j->joint;
if(r->GetAngle() > targetAngle){
r->SetMotorSpeed(-1);
} else { r->SetMotorSpeed(1); }
Basically, you see what side of the current angle the target angle is on, and then set the motor speed to move the joint in the correct direction. Hope that helps!
http://www.box2d.org/manual.html