Box2D getPosotion error Thread 1: EXC_BAD_ACCESS iPhone - ios

I am working on a game . I am facing problem in box2d.
I have created a World and a Web (sprite,body) and then i am throwing web on touchend, and a tick selector which gets position of sprite and its giving error.
Here is tick selector
onTouchEnd
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
if (freeBody) {
[self schedule: #selector(tick:)];
[self schedule:#selector(WebHitsFood:) interval:0.01f];
freeBody->SetType(b2_dynamicBody);
//this is the maximum force that can be applied
const CGFloat maxForce = 600;
//get the location of the end point of the swipe
UITouch *myTouch = [touches anyObject];
CGPoint location = [myTouch locationInView:[myTouch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
//get the rotation b/w the start point and the end point
CGFloat rotAngle = atan2f(location.y - startPoint.y,location.x - startPoint.x);
//the distance of the swipe if the force
CGFloat distance = ccpDistance(startPoint, location) * 0.5;
//put a cap on the force, too much of it will break the rope
if (distance>maxForce) distance = maxForce;
//apply force
freeBody->ApplyForce(b2Vec2(cosf(rotAngle) * distance, sinf(rotAngle) * distance), freeBody->GetPosition());
//lose the weak reference to the body for next time usage.
freeBody = nil;
}
self.isTouchEnabled = NO;
}
and Create Web Method
-(void) createWeb
{
freeBodySprite = [CCSprite spriteWithFile:#"web1.png"];//web_ani_6_1
//freeBodySprite.position = ccp(100, 300);
[self addChild:freeBodySprite z:2 tag:6];
CGPoint startPos = CGPointMake(100, 320/1.25);
bodyDef.type = b2_staticBody;
bodyDef.position = [self toMeters:startPos];
bodyDef.userData = freeBodySprite;
float radiusInMeters = ((freeBodySprite.contentSize.width * freeBodySprite.scale/PTM_RATIO) * 0.5f);
shape.m_radius = radiusInMeters;
fixtureDef.shape = &shape;
fixtureDef.density = 0.5f;
fixtureDef.friction = 1.0f;
fixtureDef.restitution = 0.0f;
circularObstacleBody = world->CreateBody(&bodyDef);
stoneFixture = circularObstacleBody->CreateFixture(&fixtureDef);
freeBody = circularObstacleBody;
}

Are you sure the GetPosition() is the problem? Try adding the line
float test = b->GetPosition().x;
just before the one giving you the issue to determine whether the issue is actually with GetPosition() or whether it is the myActor.position that is the source of the exc_bad_access.

Easy way to fix that crash:
for(b2Body* b= world->GetBodyList(); b; B->GetNext())
{
id sprite = b->GetUserData();
if( sprite && [sprite isKindOfClass:[CCSprite class])
{
CCSprite *myActor = (CCSprite*) sprite;
myActor.position = CGPointMake(b->getPosition().x*PTM_RATIO, b->getPosition().y*PTM_RATIO);
myActor.rotation = -1 * CC_RADIANS_TO_DEGREES(b->GetAngle());
}
}

Related

Change sprite image on touch

I am making a game which purpose it is to catch multiple objects that are falling from the top of the screen. In the bottom there is a basket to catch the objects. i managed to randomly spawn objects from the top dropping to the bottom using raywenderlich's tutorial : http://www.raywenderlich.com/42699/spritekit-tutorial-for-beginners
But what i want is that when i tap on that random object, the image of that object changes into another image , so just for imagination if the random objects are cats, after i tap them they have to become dogs, how do i have to program this?
edit this is what i got so far :
#import "MyScene.h"
static NSString* basketCategoryName = #"basket";
static NSString* monsterCategoryName= #"monster";
static const uint32_t projectileCategory = 0x1 << 0;
static const uint32_t monsterCategory = 0x1 << 1;
#interface MyScene() <SKPhysicsContactDelegate>
#property (nonatomic) SKLabelNode * scoreLabelNode;
#property int score;
#property (nonatomic) SKSpriteNode * basket;
#property (nonatomic) SKSpriteNode * monster;
#property (nonatomic) BOOL isFingerOnBasket;
#property (nonatomic) BOOL isFingerOnMonster;
#property (nonatomic) BOOL isTouching;
#property (nonatomic) NSTimeInterval lastSpawnTimeInterval;
#property (nonatomic) NSTimeInterval lastUpdateTimeInterval;
//#property (nonatomic, strong) SKSpriteNode *selectedNode;
#end
#implementation MyScene
-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
// Initialize label and create a label which holds the score
_score = 0;
_scoreLabelNode = [SKLabelNode labelNodeWithFontNamed:#"MarkerFelt-Wide"];
_scoreLabelNode.position = CGPointMake( CGRectGetMidX( self.frame ), 3 * self.frame.size.height / 4 );
_scoreLabelNode.zPosition = 100;
_scoreLabelNode.text = [NSString stringWithFormat:#"%d", _score];
[self addChild:_scoreLabelNode];
// Set the background
SKTexture* groundTexture = [SKTexture textureWithImageNamed:#"AcornFlipTestBackground1136x640.png"];
groundTexture.filteringMode = SKTextureFilteringNearest;
for( int i = 0; i < 2 + self.frame.size.width / ( groundTexture.size.width * 2 ); ++i ) {
SKSpriteNode* sprite = [SKSpriteNode spriteNodeWithTexture:groundTexture];
[sprite setScale:1.0];
sprite.size = CGSizeMake(self.frame.size.width,self.frame.size.height);
sprite.position = CGPointMake(CGRectGetMidX(self.frame),
CGRectGetMidY(self.frame));
[self addChild:sprite];
}
// Make grafity for sprite
self.physicsWorld.gravity = CGVectorMake(0.0f, 0.0f);
self.physicsWorld.contactDelegate = self;
// Make catching object sprite
self.basket = [SKSpriteNode spriteNodeWithImageNamed:#"bedTest.png"];
self.basket.position = CGPointMake(CGRectGetMidX(self.frame), _basket.frame.size.height * 0.5f);
self.basket.name = basketCategoryName;
[self addChild:self.basket];
// For default this is set to no until user touches the basket and the game begins.
self.isTouching = NO;
}
return self;
}
-(void)addAcorn{
if(_isTouching == YES) {
self.monster= [SKSpriteNode spriteNodeWithImageNamed:#"AcornFinal.png"];
// Determine where to spawn the monster along the X axis
int minX = self.monster.size.width;
int maxX = self.frame.size.width - self.monster.size.width;
int rangeX = maxX - minX;
int actualX = (arc4random() % rangeX)+minX;
// Random position along the X axis as calculated above
// This describe from which way the acorns move
// - means moving from top to the right and + means moving from the top to the left
self.monster.position = CGPointMake(actualX ,self.frame.size.height+ self.monster.size.height);
self.monster.name = monsterCategoryName;
[self addChild:self.monster];
CGSize contactSize = CGSizeMake(self.monster.size.width - 5.0, self.monster.size.height - 10.0);
self.monster.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:contactSize]; // 1
self.monster.physicsBody.dynamic = YES; // 2
self.monster.physicsBody.categoryBitMask = monsterCategory; // 3
self.monster.physicsBody.contactTestBitMask = projectileCategory; // 4
self.monster.physicsBody.collisionBitMask = 0; // 5
// Determine speed of the monster
int minDuration = 8.0;
int maxDuration = 10.0;
int rangeDuration = maxDuration - minDuration;
int actualDuration = (arc4random() % rangeDuration) + minDuration;
// Create the actions
SKAction * actionMove = [SKAction moveTo:CGPointMake(actualX,-self.monster.size.height) duration:actualDuration];
SKAction * actionMoveDone = [SKAction removeFromParent];
[self.monster runAction:[SKAction sequence:#[actionMove, actionMoveDone]]];
}
}
- (void)updateWithTimeSinceLastUpdate:(CFTimeInterval)timeSinceLast {
self.lastSpawnTimeInterval += timeSinceLast;
if (self.lastSpawnTimeInterval > 0.5) {
self.lastSpawnTimeInterval = 0;
[self addAcorn];
}
}
- (void)update:(NSTimeInterval)currentTime {
// Handle time delta.
// If we drop below 60fps, we still want everything to move the same distance.
CFTimeInterval timeSinceLast = currentTime - self.lastUpdateTimeInterval;
self.lastUpdateTimeInterval = currentTime;
if (timeSinceLast > 1) { // more than a second since last update
timeSinceLast = 1.0 / 60.0;
self.lastUpdateTimeInterval = currentTime;
}
[self updateWithTimeSinceLastUpdate:timeSinceLast];
}
-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
self.isTouching = YES;
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
SKNode* body = [self nodeAtPoint:location];
if ([body.name isEqualToString:basketCategoryName])
{
NSLog(#"Began touch on basket");
self.isFingerOnBasket = YES;
}
else if ([body.name isEqualToString:monsterCategoryName])
{
NSLog(#"Began touch on MONSTER");
self.isFingerOnMonster = YES;
}
}
-(void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
if (self.isFingerOnMonster) {
// 2 Get touch location
UITouch* touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
CGPoint previousLocation = [touch previousLocationInNode:self];
// 3 Get node for paddle
SKSpriteNode* monster = (SKSpriteNode*)[self childNodeWithName: monsterCategoryName];
int oldPosition = monster.position.x + (location.x - previousLocation.x);
self.monster = [SKSpriteNode spriteNodeWithImageNamed:#"AcornFinal.png"];
monster.position = CGPointMake(oldPosition, monster.position.y);
NSLog(#"reached the touch though");
}
// 1 Check whether user tapped paddle
if (self.isFingerOnBasket) {
// 2 Get touch location
UITouch* touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
CGPoint previousLocation = [touch previousLocationInNode:self];
// 3 Get node for paddle
SKSpriteNode* basket = (SKSpriteNode*)[self childNodeWithName: basketCategoryName];
// 4 Calculate new position along x for paddle
int basketX = basket.position.x + (location.x - previousLocation.x);
// 5 Limit x so that the paddle will not leave the screen to left or right
basketX = MAX(basketX, basket.size.width/2);
basketX = MIN(basketX, self.size.width - basket.size.width/2);
// 6 Update position of paddle
basket.position = CGPointMake(basketX, basket.position.y);
CGSize contactSize = CGSizeMake(basket.size.width - 8.0, basket.size.height - 8.0);
basket.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:contactSize];
basket.physicsBody.dynamic = YES;
basket.physicsBody.categoryBitMask = projectileCategory;
basket.physicsBody.contactTestBitMask = monsterCategory;
basket.physicsBody.collisionBitMask = 0;
basket.physicsBody.usesPreciseCollisionDetection = YES;
}
}
- (void)projectile:(SKSpriteNode *)basket didCollideWithMonster:(SKSpriteNode *)monster {
NSLog(#"Hit");
[monster removeFromParent];
}
- (void)didBeginContact:(SKPhysicsContact *)contact
{
// 1
SKPhysicsBody *firstBody, *secondBody;
if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask)
{
firstBody = contact.bodyA;
secondBody = contact.bodyB;
}
else
{
firstBody = contact.bodyB;
secondBody = contact.bodyA;
}
// 2
if ((firstBody.categoryBitMask & projectileCategory) != 0 &&
(secondBody.categoryBitMask & monsterCategory) != 0)
{
[self projectile:(SKSpriteNode *) firstBody.node didCollideWithMonster:(SKSpriteNode *) secondBody.node];
NSLog(#"test");
_score++;
_scoreLabelNode.text = [NSString stringWithFormat:#"%d", _score];
}
}
// Removing this void will result in being able to drag the basket accross the screen without touching the basket itself.
-(void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {
self.isFingerOnBasket = NO;
self.isFingerOnMonster = NO;
}
#end
Once a touch is detected on a sprite (I assume you already got that working out) you can either create the sprite again with spriteNodeWithImageNamed. Make sure you save the previous node's position and set it again on the new sprite so it will match the position of the old sprite.
CGPoint oldPosition = touchedSprite.position;
touchedSprite = [SKSpritNode spriteWithImageNamed:#"imgge.png"];
touchedSprite.position = oldPosition;
// If you have any other sprite properties you will have to save them as well
You can also set the texture with setTexture method which will not require you to change anything else (e.g. position) :
[touchedSprite setTexture:[SKTexture textureWithImageNamed:#"image.png"]];
EDIT :
Answering your question in the comments you implement this in the touchesEnded method of the parent node of the sprites :
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint touchLocation = [touch locationInNode:self];
for (SKSpriteNode *sprite in fallingSprites) { // Assuming fallingSprite is an array containing the cat sprites you want to detect touches for
if (CGRectContainsPoint(sprite.frame, touchLocation)) {
[sprite setTexture:[SKTexture textureWithImageNamed:#"dog.png"]];
}
}
}
Another approach (Haven't tried it yet) is to subclass SKSpriteNode and implement the same method but without the touch detection in rect since if this method is called the sprite has been touched .
Each part of the skeleton model is a spritekit node. Find the node that you wish to change and update its texture property like this:
spriteKitNode.texture = // Updated SKTexture
In your TouchesEnded event:
Add a small skspritenode positioned at the touch location with a small physics body that last for a short duration. ("touch spritenode)
Set up contact between all possible transformed objects and the "touch spritenode"
Create a subclass of SKSpritenode for the falling objects that has a variable to stores their type.
In the method called from contact between the touch spritenode and the falling objects:
Remove the touchspritenode first
Create if statements to check which falling object was touched.
Update the image of the contacted falling object spritenode according to its type.
If you are following Raywenderlich you have access to the actual syntax

Move Box2d Bodies around a Point

i have created two b2body and i want to move one body around a specific point. For this purpose, i have created two bodies and created a b2revoluteJoint between those bodies. But it doesn't produce the desired effect.
Below is my code:
-(id) init
{
if( (self=[super init])) {
self.touchEnabled = YES;
CGSize winSize = [[CCDirector sharedDirector] winSize];
b2Vec2 gravity = b2Vec2(0.0f, 0.0f);
bool allowBodiesToSleep = true;
world = new b2World(gravity);
world->SetAllowSleeping(allowBodiesToSleep);
world->SetContinuousPhysics(true);
_debugDraw = new GLESDebugDraw( PTM_RATIO );
world->SetDebugDraw(_debugDraw);
uint32 flags = 0;
flags += b2Draw::e_shapeBit;
flags += b2Draw::e_jointBit;
flags += b2Draw::e_aabbBit;
flags += b2Draw::e_pairBit;
flags += b2Draw::e_centerOfMassBit;
_debugDraw->SetFlags(flags);
// Arm
arm = [CCSprite spriteWithFile:#"arm.png"];
[self addChild:arm];
[arm setPosition:ccp(winSize.width/2, winSize.height/2)];
b2BodyDef spriteBodyDef;
spriteBodyDef.linearDamping = 1;
spriteBodyDef.angularDamping = 1;
spriteBodyDef.type = b2_dynamicBody;
spriteBodyDef.position.Set(arm.position.x/PTM_RATIO, arm.position.y+1/PTM_RATIO);
spriteBodyDef.userData = (__bridge void *)arm;
spriteBody = world->CreateBody(&spriteBodyDef);
b2PolygonShape spriteShape;
spriteShape.SetAsBox(arm.contentSize.width/PTM_RATIO/2, arm.contentSize.height/PTM_RATIO/2);
b2FixtureDef spriteShapeDef;
spriteShapeDef.shape = &spriteShape;
spriteBody->CreateFixture(&spriteShapeDef);
monster = [CCSprite spriteWithFile:#"body.png"];
[monster setPosition:ccp(winSize.width*0.37, winSize.height/2)];
[self addChild:monster];
b2BodyDef monsterBodyDef;
monsterBodyDef.position.Set(monster.position.x/PTM_RATIO, monster.position.y/PTM_RATIO);
monsterBodyDef.userData = (__bridge void *)monster;
monsterBody = world->CreateBody(&monsterBodyDef);
b2PolygonShape monsterShape;
monsterShape.SetAsBox(monster.contentSize.width/PTM_RATIO/2, monster.contentSize.height/PTM_RATIO/2);
b2FixtureDef monsterShapeDef;
monsterShapeDef.shape = &monsterShape;
monsterBody->CreateFixture(&monsterShapeDef);
b2RevoluteJointDef armJointDef;
armJointDef.Initialize(monsterBody, spriteBody, b2Vec2(monster.position.x/PTM_RATIO,monster.position.y/PTM_RATIO));
armJointDef.enableMotor = false;
armJointDef.enableLimit = true;
armJointDef.localAnchorA = b2Vec2(0, 0);
armJointDef.localAnchorB = b2Vec2(1, 0);
armJointDef.motorSpeed = -10;
armJointDef.lowerAngle = CC_DEGREES_TO_RADIANS(9);
armJointDef.upperAngle = CC_DEGREES_TO_RADIANS(75);
armJointDef.maxMotorTorque = 100;
armJoint = (b2RevoluteJoint*)world->CreateJoint(&armJointDef);
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(monster.position.x/PTM_RATIO, monster.position.y/PTM_RATIO);
//or make it static bodyDef.type = b2_staticBody;
b2Body * body = world->CreateBody(&bodyDef);
//create circle shape
b2CircleShape circle;
circle.m_radius = 20.0/PTM_RATIO;
//define fixture
b2FixtureDef fixtureDef;
fixtureDef.shape = &circle;
fixtureDef.density = 1;
fixtureDef.restitution = 0.7;
fixtureDef.friction = 0.4;
body->CreateFixture(&fixtureDef);
}
return self;
}
And touch functions to move body:
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
if (mouseJoint != nil) return;
UITouch *myTouch = [touches anyObject];
CGPoint location = [myTouch locationInView:[myTouch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
b2Vec2 locationWorld = b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO);
monster.visible = NO;
if (locationWorld.x < spriteBody->GetWorldCenter().x + 50.0/PTM_RATIO)
{
b2MouseJointDef md;
md.bodyA = monsterBody;
md.bodyB = spriteBody;
md.target = locationWorld;
md.maxForce = 2;
mouseJoint = (b2MouseJoint *)world->CreateJoint(&md);
}
}
- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *myTouch = [touches anyObject];
CGPoint location = [myTouch locationInView:[myTouch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
b2Vec2 locationWorld = b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO);
spriteBody->SetTransform(locationWorld, angle);
}
I am completely new in Box2d, so if anyone have done such thing. Kindly explain me.
Thanks :)
Not sure what you're trying here, but it seems a work for box2d joints. You could try adding a DistanceJoint to attach your dynamic bodies to a static body that will be the center.

Box2d object throwing smoother and on same velocity

I have an box2d object which i am throwing from top to bottom and i have set its speed constant but when i run it , that object has different speed sometimes and how can i make this object more smoother.
Following are some methods to show how i have created box2d world and box2d body object.
#pragma -mark Box2D World
-(void)createWorld
{
// Define the gravity vector.
b2Vec2 b_gravity;
b_gravity.Set(0.0f, -9.8f);
// Do we want to let bodies sleep?
// This will speed up the physics simulation
bool doSleep = true;
// Construct a world object, which will hold and simulate the rigid bodies.
world = new b2World(b_gravity);
world->SetAllowSleeping(doSleep);
world->SetContinuousPhysics(true);
}
-(void) createWeb
{
freeBodySprite = [CCSprite spriteWithFile:#"web1.png"];//web_ani_6_1
//freeBodySprite.position = ccp(100, 300);
[self addChild:freeBodySprite z:2 tag:6];
CGPoint startPos = CGPointMake(100, 320/1.25);
bodyDef.type = b2_staticBody;
bodyDef.position = [self toMeters:startPos];
bodyDef.userData = freeBodySprite;
float radiusInMeters = ((freeBodySprite.contentSize.width * freeBodySprite.scale/PTM_RATIO) * 0.5f);
shape.m_radius = radiusInMeters;
fixtureDef.shape = &shape;
fixtureDef.density = 0.07f;
fixtureDef.friction = 0.1f;
fixtureDef.restitution = 0.1f;
circularObstacleBody = world->CreateBody(&bodyDef);
stoneFixture = circularObstacleBody->CreateFixture(&fixtureDef);
freeBody = circularObstacleBody;
}
-(b2Vec2) toMeters:(CGPoint)point
{
return b2Vec2(point.x / PTM_RATIO, point.y / PTM_RATIO);
}
-(b2Body *) getBodyAtLocation:(b2Vec2) aLocation {
for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
{
b2Fixture* bodyFixture = b->GetFixtureList();
if (bodyFixture->TestPoint(aLocation)){
return b;
}
}
return NULL;
}
-(void) tick: (ccTime) dt
{
//It is recommended that a fixed time step is used with Box2D for stability
//of the simulation, however, we are using a variable time step here.
//You need to make an informed choice, the following URL is useful
//http://gafferongames.com/game-physics/fix-your-timestep/
int32 velocityIterations = 8;
int32 positionIterations = 3;
// Instruct the world to perform a single step of simulation. It is
// generally best to keep the time step and iterations fixed.
world->Step(dt, velocityIterations, positionIterations);
//Iterate over the bodies in the physics world
for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
{
if (b->GetUserData() != NULL) {
//Synchronize the AtlasSprites position and rotation with the corresponding body
CCSprite *myActor = (CCSprite*)b->GetUserData();
myActor.position = CGPointMake( b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO);
myActor.rotation = -1 * CC_RADIANS_TO_DEGREES(b->GetAngle());
}
}
}
This is my touch Event where i am getting angle and speed to throw .
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
//get the location of the end point of the swipe
UITouch *myTouch = [touches anyObject];
CGPoint location = [myTouch locationInView:[myTouch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
//CCLOG(#"Start -> %0.f || End -> %0.f",startPoint.x,location.x);
if (freeBody) {
//[self calcAngleAndRotateObjectStartingAtPoint:startPoint endingAtPoint:location];
self.isTouchEnabled = NO;
freeBody->SetType(b2_dynamicBody);
//this is the maximum force that can be applied
const CGFloat maxForce = 20;
//get the rotation b/w the start point and the end point
CGFloat rotAngle = atan2f(location.y - startPoint.y,location.x - startPoint.x);
//the distance of the swipe if the force
CGFloat distance = ccpDistance(startPoint, location) * 0.5;
//if (distance>maxForce)
distance = maxForce;
//else
// distance = 10;
//apply force
freeBody->ApplyForce(b2Vec2(cosf(rotAngle) * distance, sinf(rotAngle) * distance), freeBody->GetPosition());
//lose the weak reference to the body for next time usage.
freeBody = nil;
}
}
This is code i am using to throw , but sometimes its speed is faster and some time slower , and i have set maxForce = 20 for constant speed.
As the comment above world->Step() dictates, you should use fixed dt. Verify that dt is fixed and world->Step() is being called at regular interval.
Finnally i have solved this problem. i changed ApplyForce with SetLinearVelocity..
here is the code.
float spd = 10;
b2Vec2 velocity = spd*b2Vec2(cos(rotAngle), sin(rotAngle));
freeBody->SetLinearVelocity(velocity);

how to move one object over another object without bounce in box2d in iphone?

I want to move one object over another object without bounce when they collide.
In Simple i have one ball(body) and i have one Rectangular line image(body), the image is slope 45 degree.
The ball fall from the top speed is 20 when the ball touch on the slope image(Static Body) it will bounce always and continue running.
When the ball come over the line image it will not bounce and slow down the speed according to the collision and ball stop in the end. Same as it happens in real world when ball collide with something , the ball speed will slow down and it turn according to the collision and then stop due to decreasing speed of collision.
I am doing this, but cant achieve the result what i want.
-(id) init
{
if( (self=[super init])) {
CGSize winSize = [CCDirector sharedDirector].winSize;
// Create a world
b2Vec2 gravity = b2Vec2(0.0f, 0.0f);
_world = new b2World(gravity);
///////////////////////// Ball ///////////////////////////////
// Create sprite and add it to the layer
CCSprite *ball = [CCSprite spriteWithFile:#"ball.png"];
ball.position = ccp(100, 200);
ball.tag = 1;
[self addChild:ball];
// Create ball body
b2BodyDef ballBodyDef;
ballBodyDef.type = b2_dynamicBody;
ballBodyDef.position.Set(127/PTM_RATIO, 210/PTM_RATIO);
ballBodyDef.userData = ball;
ballBody = _world->CreateBody(&ballBodyDef); // b2Body * ballBody
// Create circle shape
b2CircleShape circle;
circle.m_radius = 26.0/PTM_RATIO;
// Create shape definition and add to body
b2FixtureDef ballShapeDef;
ballShapeDef.shape = &circle;
ballShapeDef.density = 15.0f;
ballShapeDef.friction = 2.f;
ballShapeDef.restitution = 0.0f;
_ballFixture = ballBody->CreateFixture(&ballShapeDef);
b2Vec2 force = b2Vec2(73, -52);
ballBody->ApplyLinearImpulse(force, ballBodyDef.position);
//ballBody->SetLinearVelocity(b2Vec2(10,0)); // try
// ballBody->SetAngularVelocity(0); // try
///////////////////////// Ball ///////////////////////////////
// Create paddle and add it to the layer
CCSprite *paddle = [CCSprite spriteWithFile:#"paddle.png"];
paddle.position = ccp(winSize.width/2, 50);
[self addChild:paddle];
// Create paddle body
b2BodyDef paddleBodyDef;
paddleBodyDef.type = b2_staticBody; //b2_staticBody, b2_dynamicBody
paddleBodyDef.position.Set(winSize.width/2/PTM_RATIO, 50/PTM_RATIO);
paddleBodyDef.userData = paddle;
paddleBodyDef.angle = 75;
_paddleBody = _world->CreateBody(&paddleBodyDef);
// Create paddle shape
b2PolygonShape paddleShape;
paddleShape.SetAsBox(paddle.contentSize.width/PTM_RATIO/2, paddle.contentSize.height/PTM_RATIO/2);
// Create shape definition and add to body
b2FixtureDef paddleShapeDef;
paddleShapeDef.shape = &paddleShape;
paddleShapeDef.density = 25.0f;
paddleShapeDef.friction = 1.1f;
paddleShapeDef.restitution = 0.1f;
_paddleFixture = _paddleBody->CreateFixture(&paddleShapeDef);
// Restrict paddle along the x axis
b2PrismaticJointDef jointDef;
b2Vec2 worldAxis(0.0f, 0.0f);
jointDef.collideConnected = true;
jointDef.Initialize(_paddleBody, _groundBody, _paddleBody->GetWorldCenter(), worldAxis);
_world->CreateJoint(&jointDef);
[self schedule:#selector(tick:)];
self.touchEnabled = YES;
}
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if (_mouseJoint != NULL) return;
UITouch *myTouch = [touches anyObject];
CGPoint location = [myTouch locationInView:[myTouch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
b2Vec2 locationWorld = b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO);
if (_paddleFixture->TestPoint(locationWorld)) {
b2MouseJointDef md;
md.bodyA = _groundBody;
md.bodyB = _paddleBody;
md.target = locationWorld;
md.collideConnected = true;
md.maxForce = 1000.0f * _paddleBody->GetMass();
_mouseJoint = (b2MouseJoint *)_world->CreateJoint(&md);
_paddleBody->SetAwake(true);
}
// [self kick];
}
-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
if (_mouseJoint == NULL) return;
UITouch *myTouch = [touches anyObject];
CGPoint location = [myTouch locationInView:[myTouch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
b2Vec2 locationWorld = b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO);
_mouseJoint->SetTarget(locationWorld);
}
Ok so You have mad very small mistak, problem is with gravity.
change it to
b2Vec2 gravity = b2Vec2(0.0f, -10.0f);

how to allow zooming without showing black background near borders in ios

if touchlocation for zoom is near the corners, black background shown and not zoomed to correct location i want.
i want to zoom to touch location but not showing black background. staying with borders
i think it is better to explain with code and screen shots.
note:tileMap size is 800x480 so i scale it to 480x320..
- (id) init {
if( (self=[super init]) ) {
self.scaleY=0.66f;
self.scaleX=0.6f;
self.anchorPoint = ccp(0,0);
....
}
- (void)handleDoubleTapFrom:(UITapGestureRecognizer *)recognizer {
CGPoint touchLocation = [recognizer locationInView:[[CCDirector sharedDirector]view] ];
if(!isGameFinished){
if(zoomPerformed == NO ) {
id zoomIn = [CCScaleTo actionWithDuration:0.3f scale:1];
id sequence = [CCSequence actions:zoomIn, nil];
[self runAction:sequence ];
CGSize winSize = [[CCDirector sharedDirector] winSize];
CGPoint center = ccpMult(ccpFromSize(winSize),0.5);
center.x = center.x / ((800/480)/0.666f);
center.y = center.y / 0.666f;
CGPoint zoomPoint =ccpSub(center,touchLocation);
zoomPoint = [self myBoundaries:zoomPoint];
zoomPoint.y = -1 * zoomPoint.y;
[self runAction:[CCMoveBy actionWithDuration:0.3f position:zoomPoint]];
zoomPerformed = YES;
self.anchorPoint = ccp(0,0);
}else{
zoomPerformed = NO;
id moveto = [CCMoveTo actionWithDuration:0.3f position:ccp(0,0)];
id zoomIn = [CCScaleTo actionWithDuration:0.3f scaleX:0.6 scaleY:0.666];
id sequence = [CCSequence actions:moveto,zoomIn, nil];
[self runAction:sequence];
self.anchorPoint = ccp(0,0);
}
}
}
-(CGPoint)myBoundaries:(CGPoint)distanceToCenter{
CGSize tileSize = self.tileMap.boundingBox.size;
CGPoint moveBySize = ccpMult(distanceToCenter,(tileSize.width/tileSize.height));
moveBySize.x = (moveBySize.x*0.6f);
moveBySize.y = (moveBySize.y*0.666f) ;
return moveBySize;
}

Resources