How to apply force at an speicific angle in spriteKit? - ios

I want to give Force to my SKSpriteNode at specific angle.
So, How to treat my CGVector for give force at specific angle?
I had searched for it but unfortunately not getting any good way.
What i wants to achieve :
My SKSpriteNode moving towards the screen. There are buttons on top like 30,45,60.
So if user press button(i.e. that Button contain "30") then i had to move my SKSpriteNode to 30 degree with same speed.
Please help me towards it if any of you can help me regarding this.

First, you will need to convert the angle in degrees to radians by multiplying it by pi / 180
CGFloat angleInRadians = angleInDegrees * M_PI / 180;
You can then determine the vector components in that direction by
CGFloat dx = cosf(angleInRadians);
CGFloat dy = sinf(angleInRadians);
and finally apply a force to the sprite with
[sprite.physicsBody applyForce:CGVectorMake(dx*scale, dy*scale)];
where scale determines how much force is applied.
Optionally, you can rotate the sprite to face in the same direction as its motion by
sprite.zRotation = angleInRadians + offset;
where offset is the difference in angle, in radians, between your sprite's image and zero degrees. For example, if your sprite is facing up when zRotation is zero, offset should be -M_PI_2.

Related

Get the actual angle after the superview is rotated

I have 5 subviews(White) added to the superview(Gray), when I rotate the superview I want to know the angle(like 1 and 2) of each of the subview with the red circle.(the center of the subviews and the red circle are ON the same circle)
Start Position:
Rotated Position:
From your comment you appear to want to determine the coordinates of the centres of your five circles for a given rotation. The centres will all lie on a circle. So your question boils down to what are the coordinates of a point on a circle of radius r for an angle θ. The parametric equations for a circle give you that:
x = r cos θ
y = r sin θ
The angle, θ, in these equations is measured in radians from the positive x-axis in an anti-clockwise direction. If your angle are in degrees you will find the M_PI constant for π useful as:
360 degrees = 2 π radians
The rest is simple math, take your angle of rotation to give you the angle for A (remembering to adjust for 0 being the x-axis and measuring anti-clockwise if needed), the other centres are multiples of 72 degrees (0.4 π radians) from this.
HTH
I'm not sure I completely understand your question, but if you just need to take a known point and rotate it a certain number of degrees, check out the docs for CGAffineTransform.
For example:
CGAffineTransform rotation = CGAffineTransformMakeRotation (angle);
CGPoint rotatedPoint = CGPointApplyAffineTransform (startingPoint, rotation);
This rotation matrix is around (0, 0) and the angle is in radians, so you will need to subtract the center of your superview's bounds to get an offset relative to the center, do the rotation, and add back in the center. Or you can build an affine transform made up of that translation, rotation, and inverse translation, and then apply that to your starting point as above.
Given that you already seem to know the main rotation angle, this will give you the angles in the range -180 .. +180 and positions of each of the white discs:
GCFloat toRads = M_PI / 180.0;
CGFloat angleA = self.rotationInDegrees;
if (angleA > 180) angleA -= 360;
CGFloat xA = self.radius * sinf(angleA * toRads);
CGFloat yA = self.radius * cosf(angleA * toRads);
CGFloat angleB = angleA + 72;
if (angleB > 180) angleB -= 360;
CGFloat xB = self.radius * sinf(angleB * toRads);
CGFloat yB = self.radius * cosf(angleB * toRads);
etc...
(This assumes your zero degrees is from the vertical. If it's from the horizontal swap cos and sin over).

Not enough precision for points in CGPoint type

I'm developing map-based game using cocos2d v3.
I have a map with size of 2^19 points. On that map I have object that should move over time in short distance. About 60-70 points.
CGPoint offset = [_trajectoryPath offsetForNextPosition];
CGFloat x = self.position.x + offset.x;
CGFloat y = self.position.y + offset.y;
self.position = CGPointMake(x, y);
At such map size map position can be something like {300000, 40000} points.
When I try to add small step, lets say about {0.002f, 0.004f}, to animate object position I end up with still the same {300000, 40000} points...
I understand that it happens because of precision of float. Values normalised by map size, to be between 0 and 1.0, don't work either.
Is it possible somehow to increase precision of float type on iOS? Or may be someone cam give a hint about possible workaround for this problem?
Thanks.
mightee.cactus, I remember we had a similar issue while adding very small numbers to very large ones with float in c.
The solution was follows: we changed types to double to preserve accuracy; in your case you can make all the arithmetic operations with doubles and translate them into CGFloat just before use in CGPointMake.

Converting position with regarding anchorPoint?

I have a sprite, which is added to CCSpriteBatchNode. Then I fix position of the sprite, changing anchor point the way so I can rotate sprite around that point.
Hierarchy is sprite <- batchNode <- scene
Basically sprite is moving but it's .position property is not changing. I need to get the real position of the sprite after transformations. So I tried to use
CGPoint p = sprite.position;
p = [sprite convertToWorldSpace:p];
However, position is not matching to the sprite's position which I see in the scene.
Sprite position is a point at the middle of the CCSprite(by default). Changing the anchor point moves the sprite such that the point moves with respect to the sprite but remains same with respect to the world space. For example, changing the anchor point of a sprite(say square) to ccp(0,0) will move the square so that its bottom left vertex will come at the position where the square's center point was initially. So while the square may seem to be "repositioned" ,its position (property) stays the same(unaffected by change in anchor point) unless specifically changed.
EDIT
If by real position of the sprite, you mean its mid point after its anchor point has been changed then it can be calculated by taking into account the two transformations that have been applied on it i.e. Translation and Rotation.
First we take care of Translation:
Your sprite has moved by:
CGPoint translation;
translation.x = sprite.contentSize.width x (0.5 - sprite.anchorPoint.x);
translation.y = sprite.contentSize.height x (0.5 - sprite.anchorPoint.y);
Now we accomodate for change in Rotation
Converting "translation" point into polar coordinates we get
#define RADIANS_TO_DEGREES(radians) ((radians) * (180.0 / M_PI))
r = ccpDistance(translation,ccp(0,0));
ø = RADIANS_TO_DEGREES(atan2(translation.x,translation.y)); //i take x/y here as i want the CW angle from y axis.
If you rotated your sprite by "D" degrees:
ø = ø + D;
CGPoint transPositionAfterRotation = ccp(r * cos(ø),r * sin(ø) );
CGPoint realPosition = ccp(sprite.position.x + transPositionAfterRotation.x, sprite.position.y +transPositionAfterRotation.y)

How to draw line given a center point and angle in iOS?

This is so much an iOS question as it is my current inability to do coordinate geometry. Given a CGPoint to act as a point that the line will pass through and an angle in radians. How do I draw a line that extends across to the bounds of the screen (infinite line)?
I am using Quartz2d to do this and the API for creating a line is limited to two points as input. So how do I convert a point and angle to two points on the bounds of the iOS device?
This begins with simple trigonometry. You need to calculate the x and y coordinate of the 2nd point. With an origin of 0,0 and treating a line that goes straight to the right as 0 degrees, and going counterclockwise (anti-clockwise for some of you), you do:
double angle = ... // angle in radians
double newX = cos(angle);
double newY = sin(angle);
This assumes a radius of 1. Multiply each times a desired radius. Pick a number that will be bigger than the screen such as 480 for an iPhone or 1024 for an iPad (assuming you want points and not pixels).
Then add the original point to get the final point.
Assuming you have CGPoint start, double angle, and a length, your final point is:
double endX = cos(angle) * length + start.x;
double endY = sin(angle) * length + start.y;
CGPoint end = CGPointMake(endX, endY);
It's OK if the end point is off the screen.

How to determine closest CGPoint with an angle and another CGPoint

I calculate angle between two CGPoints :
//calculate radian and degree
CGPoint diff = ccpSub(center, location);//return ccp(v1.x - v2.x, v1.y - v2.y);
float rads = atan2f( diff.y, diff.x);
float degs = -CC_RADIANS_TO_DEGREES(rads);
NSLog(#"Rad %.2f Degs %.2f",rads,degs);
Now In another function where I have a pre known CGPoint and the degree of above function, I want to calculate closest point that satisfies the degree.
I was thinking about maybe below code would help me but in below code start point and rotation point is known, in my situation I only know start point.
-(void) rotateAroundPoint:(CGPoint)rotationPoint angle:(CGFloat)angle {
CGFloat x = cos(CC_DEGREES_TO_RADIANS(-angle)) * (self.position.x-rotationPoint.x) - sin(CC_DEGREES_TO_RADIANS(-angle)) * (self.position.y-rotationPoint.y) + rotationPoint.x;
CGFloat y = sin(CC_DEGREES_TO_RADIANS(-angle)) * (self.position.x-rotationPoint.x) + cos(CC_DEGREES_TO_RADIANS(-angle)) * (self.position.y-rotationPoint.y) + rotationPoint.y;
Lets say I have a point 800,600 and I have a degree of 70, how can I calculate closest point with that point and that degree?
EDIT:::
Normally in my game sprites are moved with a button therefore all rotation,movement,speed etc are handled when button pressed [sprite moveToPreGivenPostion:CGPoint]
But now a compass is added and when user choose an angle on the compass I need to move the sprite in the direction of degree on compass, since [sprite moveToPreGivenPostion:CGPoint] already handles rotation and other stuff I just want to determine that what CGPoint should I send to moveToPreGivenPostion function.
As #trumpetlicks said you cant find the closest point like that, but I guess I understood what you want and that function -(void) rotateAroundPoint:(CGPoint)rotationPoint angle:(CGFloat)angle you are trying to use is perfectly fine to achieve what you want.
all you need to do is choose float radius.
you know your current point and lets say your radius is 1, basically you can calculate your previous point without a degree, assuming 0 degrees is left of your point and lets say your point is 200,200 with 1 radius 0 degree your previous point automatically becomes 199,200.
So now you have a reference point so now calculate the point you want to move your sprite:
//choose a feasable radius
float radius = 0.5;
//position_ is your preknown position as you said
//find a the point to roate
//position_.x-radius is always 0 degrees of your current point
CGFloat x = cos(rads) * ((position_.x-radius)-position_.x) - sin(rads) * ((position_.y)-position_.y) + position_.x;
CGFloat y = sin(rads) * ((position_.x-radius)-position_.x) + cos(rads) * ((position_.y)-position_.y) + position_.y;
//get the new point
CGPoint newLocation = ccp(x, y);

Resources