Moving a sprite with touches began, casting and parameters in obj - c? - iphone

I've been reading a book on the cocos2d framework for ios5 for a few days and have developed a small game that the book walks you through. To control the sprite in this game you use the accelerometer:
-(void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
float deceleration = 0.4f;
float sensitivity = 6.0f;
float maxVelocity = 100;
// adjust velocity based on current accelerometer acceleration
playerVelocity.x = playerVelocity.x * deceleration + acceleration.x * sensitivity;
// we must limit the maximum velocity of the player sprite, in both directions (positive & negative values)
if (playerVelocity.x > maxVelocity)
{
playerVelocity.x = maxVelocity;
}
else if (playerVelocity.x < -maxVelocity)
{
playerVelocity.x = -maxVelocity;
}
// Alternatively, the above if/else if block can be rewritten using fminf and fmaxf more neatly like so:
// playerVelocity.x = fmaxf(fminf(playerVelocity.x, maxVelocity), -maxVelocity);
}
Now I'm wondering if I can change this code to allow the sprite to still accelerate/decelerate along the x axis, but to use touch input rather than the accelerometer, and to go faster the longer the touch is held down for? So a touch to the right would move the sprite to that spot slowly, if the touch is released, it stops moving to that spot. The longer a touch is held down, the faster the sprite moves.
is there anything in the framework to allow me to implement a rotation mechanism that allows my sprite to rotate to the position that the touch was in, so it looks like its facing the point thats been touched?

Well, afaik theres no method that will determine the angle to the touch and then rotate the sprite accordingly, but if you have the x and y coordinates of the sprite and the touch you can calculate it yourself fairly easily.
CGPoint spriteCenter; // this should represent the center position of the sprite
CGPoint touchPoint; //location of touch
float distanceX = touchPoint.x - spriteCenter.x;
float distanceY = touchPoint.y - spriteCenter.y;
float angle = atan2f(distanceY,distanceX); // returns angle in radians
// do whatever you need to with the angle
Once you have the angle you can set the rotation of the sprite.

Related

apply force to a body in touchesMoved direction in box2d iphone

I am new to box2d. I have a problem i.e
when i touch the body and touchmoved(In touchmoved method i don't want move the body)upto some place and touch released.
in touchend i apply force like this...
b2Vec2 force = b2Vec2(0.0,15.0);
ballBody->SetLinearVelocity(force);
and find out the angle b/w touchbegin point to touchend point in this way
float angleRadians = atan2(touchBegin.x - touchEnd.x, touchBegin.y - touchEnd.y);
float angleDegrees = CC_RADIANS_TO_DEGREES(angleRadians);
cocosAngle1 = -1 * angleDegrees;
in that time,how to apply force to the body with cocosAngle1(touchend direction). Like paper in "Paper Toss" game.
how to apply force in touchmoved direction of body?...
please explain to me...

Move object into screen without gravity into box2d in iPhone

i use following code to move my Box2D object into screen, but because gravity of my world or something else i dont know why my objects is forced to move down, i am new to box2d.
i want to move my object in entire world without gravity.
-(void) tick:(NSTimer *)timer {
int32 velocityIterations = 8;
int32 positionIterations = 1;
world->Step(1.0f/60.0f, velocityIterations, positionIterations);
for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
{
if (b->GetUserData() != NULL)
{
UIView *oneView = (UIView *)b->GetUserData();
CGPoint newCenter = CGPointMake(b->GetPosition().x * PTM_RATIO,self.view.bounds.size.height - b->GetPosition().y * PTM_RATIO);
oneView.center = newCenter;
CGAffineTransform transform = CGAffineTransformMakeRotation(- b->GetAngle());
oneView.transform = transform;
}
}
}
my accelerometer code is as follow.
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
b2Vec2 gravity;
gravity.Set( acceleration.x * 1.81, acceleration.y * 1.81 );
world->SetGravity(gravity);
}
pleas if any one work around.
Thanks.
As i understand you want to move your object setting it's position. It's a bad idea because it will provide non-physical behavior of the bodies colliding with your object. That's because if you will only change the position of your body it's velocity for physics engine will be still zero and collision will be processed according to zero speed of your object.
A better solution is to use b2_kinematicBody type for your object. Then you will be able to control it's motion specifying it's velocity vector and physics will behave as expected. Also the gravity (and no other forces) will not be applied to your object because of it's type.
EDIT
//creation
b2BodyDef bDef;
bDef.type = b2_kinematicBody;
bDef.position.Set(5, 6);
b2Body *body = physWorld->CreateBody(&bDef);
//control
body->SetLinearVelocity(b2Vec2(3, 4));

cocos2d rotating sprite collision detection

I got 2 sprites, ball and arrow.
the arrow is not moving.
the ball is rotating on it's anchor point.
id rotate = [CCRotateBy actionWithDuration:.5 angle: 360];
I want to detect collision when the ball reaches to arrow.
Tried CGRectIntersectsRect but it does not detect collision.
Any help?
Thanks...
You probably don't want this answer, but I would use Box2D or Chipmunk and use the Vertex Helper application to specify vertices.
use circle-circle collision method.. here is the method..
-(float)asbs:(CGPoint)_arrowPos ballPos:(CGPoint)_ballPos
{
float x = _arrowPos.x-_ballPos.x;
float y = _arrowPos.y-_ballPos.y;
float xy = x*x+y*y;
return xy;
}
if([self asbs:arrow.position ballPos:ball.position]<=size)
{
//collision
}
note that size = ball radius + arrow radius * ball radius + arrow radius
the method above is using a(square) + b(square) = c(square) to check distance between two points..
You might need to convert the ball to world space in an update method then call that rather than the balls position. If it is in a parent layer is position will always be static in respect to its parent.

how to rotate a UIView to face a point

I have a UIView that I want to rotate when I move my finger across the screen (like in a circle). I want the UIView to rotate so that it faces my touchpoint. I then want to shoot something from my UIView (like a bullet) in the direction that the UIView is facing. Any Ideas???
Glad I remember triginometry
-(void)degreesToRotateObjectWithPosition:(CGPoint)objPos andTouchPoint:(CGPoint)touchPoint{
float dX = touchPoint.x-objPos.x; // distance along X
float dY = touchPoint.y-objPos.y; // distance along Y
float radians = atan2(dY, dX); // tan = opp / adj
//Now we have to convert radians to degrees:
float degrees = radians*M_PI/360;
return degrees;
}
Once you have your nice method, just do this:
CGAffineTransform current = view.transform;
[view setTransform:CGAffineTransformRotate(current, [view degreesTorotateObjectWithPosition:view.frame.origin andTouchPoint:[touch locationInView:parentView]]
//Note: parentView = The view that your object to rotate is sitting in.
This is pretty much all the code that you'll need.The math is right, but I'm not sure about the setTransform stuff. I'm at school writing this in a browser. You should be able to figure it out from here.
Good luck,
Aurum Aquila

How to rotate image around center point automatically with finger touch

On iPhone, how to implement rotating image around the center point using finger touch ?
Just like wheel, if you put finger on the iPhone screen , then move suddenly, then the image becoming rotating around center point just like the wheel, after a while, it becomes more and more slow , finally stop.
Who can help to give some pieces of codes (Object-C) or some suggest ?
I was working with a "spin the bottle"-app yesterday. On the window I have a ImageView with an bottle that's suppose to response to touches and rotate the way the user swipes his finger. I struggled to get my ImageView to rotate during the touch-events (TouchesBegan, Touchesoved, TouchesEnd). I used this code in TouchesMoved to find out the angle in witch to rotate the image.
public override void TouchesMoved (NSSet touches, UIEvent evt)
{
PointF pt = (touches.AnyObject as UITouch).LocationInView(this);
float x = pt.X - this.Center.X;
float y = pt.Y - this.Center.Y;
double ang = Math.Atan2(x,y);
// yada yada, rotate image using this.Transform
}
THIS IS IMPORTANT! When the ImageView rotates, even the x & y-coordinates changes. So touching the same area all the time would give me different values in the pt and prePt-points. After some thinking, googeling and reading I came up with an simple solution to the problem. The "SuperView"-property of the ImageView.
PointF pt = (touches.AnyObject as UITouch).LocationInView(this.SuperView);
Having that small change in place made it alot easier, no i can use the UITouch-metohs LocationInView and PreviousLocationInView and get the right x & y coordinates. Her is parts of my code.
float deltaAngle;
public override void TouchesMoved (NSSet touches, UIEvent evt)
{
PointF pt = (touches.AnyObject as UITouch).LocationInView(this.Superview);
float x = pt.X - this.Center.X;
float y = pt.Y - this.Center.Y;
float ang = float.Parse(Math.Atan2(dx,dy).ToString());
//do the rotation
if (deltaAngle == 0.0) {
deltaAngle = ang;
}
else
{
float angleDif = deltaAngle - ang;
this.Transform = CGAffineTransform.MakeRotation(angleDif);
}
}
Hope that helped someone from spending hours on how to figure out how to freaking rotate a bottle! :)
I would use the affine transformations - yuou can assign a transformation to any layer or UI element using the transform property.
You can create a rotation transform using CGAffineTransform CGAffineTransformMakeRotation( CGFloat angle) which will return a transformation that rotates an element. The default rotation should be around the centerpoint.
Be aware, the rotation is limited to 360 degrees, so if you want to rotate something more than that (say through 720 degrees) - you have to break the rotation into several sequences.
You may find this SO article useful as well.
The transform property of a view or layer can be used to rotate the image displayed within. As far as the spinning part goes, you just track the location and movement of touches in your view with touchesBegan, touchesMoved, and touchesEnded.
Use the distance and time between the touches updates to calculate a speed, and use that to set a rotational velocity. Once you start the image spinning, update the position periodically (with an NSTimer, maybe), and reduce the rotational velocity by some constant.