Bouncing nodes get crazy - ios

I am building a little game, but have a problem. I made some balls which bounce in the screen, it's the intention that the bounce in the screen with the same speed. My problem is the fact that after like 30 seconds the balls go crazy en bounce over the screen as fast as possible. How can I fix it?
Here's my code:
int maxXCoord = self.frame.size.width;
int maxYCoord = self.frame.size.height;
int circleWidth = 6;
int x = arc4random() % (maxXCoord - (circleWidth / 2));
int y = arc4random() % (maxYCoord - (circleWidth / 2));
SKSpriteNode* _numberint = [SKSpriteNode spriteNodeWithImageNamed: #"red.png"];
_numberint.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:(_numberint.frame.size.width/2)];
_numberint.position = CGPointMake(x,y);
_numberint.physicsBody.contactTestBitMask = ballCatagoryName;
_numberint.physicsBody.collisionBitMask = ballCatagoryName;
_numberint.physicsBody.friction = 0.8f;
_numberint.physicsBody.restitution = 1.2f;
_numberint.physicsBody.linearDamping = 0.0f;
_numberint.physicsBody.angularDamping = 0.0f;
_numberint.physicsBody.allowsRotation = NO;
[_numberint.physicsBody applyImpulse:CGVectorMake(8.0f, -8.0f)];
[self addChild:_numberint];
Thank you!

If you set restitution to values above 1.0 the objects will pick up speed with every collision. Set restitution to 1.0 or below.

Related

Spritekit PhysicsBody applyTorque

I'm working on a universal app.
I want to applyTorque to a Paddle
But the problem is the paddle sizes are bigger on a ipad than the one one iphone.
How can I calculate the torque to apply the same affect to the Paddle's physicalBody?
SKSpriteNode *bar = [SKSpriteNode spriteNodeWithImageNamed:nameImage];
bar.name = #"bar";
bar.size = CGSizeMake(PaddleWidth, PaddleHeight);
bar.physicsBody =[SKPhysicsBody bodyWithTexture:bar.texture size:bar.size];
bar.physicsBody.restitution = 0.2;
bar.physicsBody.angularDamping = 0;
bar.physicsBody.friction = 0.02;
bar.physicsBody.mass=.2;
[paddle addChild:bar];
SKSpriteNode *anchor = [SKSpriteNode spriteNodeWithColor:[SKColor clearColor] size:CGSizeMake(PaddleWidth, PaddleHeight)];
anchor.name = #"anchor";
anchor.size = CGSizeMake(PaddleHeight, PaddleHeight);
anchor.position = CGPointMake(bar.position.x + bar.size.width/2, 0);
[paddle addChild:anchor];
CGFloat anchorRadius = anchor.size.width/20;
anchor.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:anchorRadius];
anchor.physicsBody.dynamic = NO;
CGPoint positionInScene = [self convertPoint:anchor.position toNode:self.scene];
pin = [SKPhysicsJointPin jointWithBodyA:bar.physicsBody
bodyB:anchor.physicsBody
anchor:positionInScene];
pin.shouldEnableLimits = YES;
pin.lowerAngleLimit = -0.5;
pin.upperAngleLimit = 0.5;
[self.scene.physicsWorld addJoint:pin];
-(void)flip{
SKNode *bar=[self childNodeWithName:#"bar"];
CGFloat torque;
torque=10;
[bar.physicsBody applyTorque:torque];
}
You can use the size of the paddle as a factor in the torque value:
CGSize paddleSize = <Initialize with paddle size>
CGFloat torque=paddleSize.width * factor; // factor will be the value you need to multiply in order to reach your desired value
So if for example paddle width is 100 use a constant factor of 0.05
On the iPad the different paddle width will make the torque value to be calculated accordingly using the same factor value as above.
You can set a constant mass of the physicsBody so that the torque applied affects the paddle the same way regardless of the node's size.
//While instantiating the physicsBody for the "bar" node
bar.physicsBody.mass = 0.2; //This will need to be adjusted according to your needs.
From the documentation:
The mass of the body affects its momentum as well as how forces are
applied to the object.

figuring out the conversions from UIKit coordinates to SKScene coordinates

I am new to SpriteKit but not to iOS. I'm having a great deal of difficulty figuring out the conversions from UIKit coordinates to SKScene coordinates. In addition, their relations to the units used for the SpriteKit physics engine evades me.
Here's what I'm trying to do: I am launching a sprite with an initial velocity in both x and y directions. The sprite should start near the screen's bottom left corner (portrait mode) and leave near the bottom right corner. Another sprite should appear somewhere on the previous sprite's trajectory. This sprite is static.
The blue frame is the screen boundary, the black curve is the first sprite's trajectory and the red circle is the static sprite.
Now using the screen as 640 x 960. In my SKScene's didMoveToView: method I set the gravity as such:
self.physicsWorld.gravity = CGVectorMake(0.0f, -2.0f);
Then I make the necessary calculations for velocity and position:
"t" is time from left corner to right;
"y" is the maximum height of the trajectory;
"a" is the acceleration;
"vx" is velocity in the x direction;
"vy" is velocity in the y direction;
and
"Tstatic" is the time at which the dynamic sprite will be at the static sprite's position;
"Xstatic" is the static sprite's x-position;
"Ystatic" is the static sprite's y-position;
-(void)addSpritePair {
float vx, vy, t, Tstatic, a, Xstatic, Ystatic, y;
a = -2.0;
t = 5.0;
y = 800.0;
vx = 640.0/t;
vy = (y/t) - (1/8)*a*t;
Tstatic = 1.0;
Xstatic = vx*Tstatic;
Ystatic = vy*Tmark + 0.5*a*Tstatic*Tstatic;
[self spriteWithVel:CGVectorMake(vx, vy) andPoint:CGPointMake(xmark, ymark)];
}
-(void)spriteWithVel:(CGVector)velocity andPoint:(CGPoint)point{
SKSpriteNode *staticSprite = [SKSpriteNode spriteNodeWithImageNamed:#"ball1"];
staticSprite.anchorPoint = CGPointMake(.5, .5);
staticSprite.position = point;
staticSprite.name = #"markerNode";
staticSprite.zPosition = 1.0;
SKSpriteNode *dynamicSprite = [SKSpriteNode spriteNodeWithImageNamed:#"ball2"];
dynamicSprite.anchorPoint = CGPointMake(.5, .5);
dynamicSprite.position = CGPointMake(1 ,1);
dynamicSprite.zPosition = 2.0;
dynamicSprite.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:hoop.size.width/2];
dynamicSprite.physicsBody.allowsRotation = NO;
dynamicSprite.physicsBody.velocity = velocity;
dynamicSprite.physicsBody.affectedByGravity = YES;
dynamicSprite.physicsBody.dynamic = YES;
dynamicSprite.physicsBody.mass = 1.0f;
dynamicSprite.markerPoint = point;
dynamicSprite.physicsBody.restitution = 1.0f;
dynamicSprite.physicsBody.friction = 0.0f;
dynamicSprite.physicsBody.angularDamping = 0.0f;
dynamicSprite.physicsBody.linearDamping = 0.0f;
[self addChild:hoop];
[self addChild:marker];
}
When I execute the code, the following happens:
Can someone please help me out?

SpriteNodes stop moving in the middle of the screen

I'm building a game using spriteKit.
I created a spriteNode called 'planet' and set a velocity. It drops down from the top of the screen with constant speed to the bottom of the screen. However, it slows down towards the middle of the screen and stops moving entirely. I added the method 'moveTowardPosition' as an attempt to fix this issue by forcing the objects to move offscreen. Does anyone have an idea of what the issue might be?
Thanks!
Here is the setup of the object:
-(void)physicsBodySetup
{
//initializes the physicsBody
self.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:40];
self.physicsBody.affectedByGravity = NO;
//sets its category mask
self.physicsBody.categoryBitMask = TKCollisionCategoryPlanet;
//planet doesn't collide with anything
self.physicsBody.collisionBitMask = 0;
//the planet can get into contact with an astranaut
self.physicsBody.contactTestBitMask = TKCollisionCategoryAstronaut |
}
//adds 'planet' to the screen at random position
//#param frame: the frame of the main view
-(void)addPosition:(CGRect)frame
{
//specifies a random position to add the planet on the screen
float randomPositionY = frame.size.height + self.size.height;
float randomPositionX = [TKUtil randomWithMin:10+self.size.width max:frame.size.width-10 - self.frame.size.width];
self.position = CGPointMake(randomPositionX, randomPositionY);
[self velocitySetup];
}
-(void)velocitySetup
{
//initializes the speed to be a constant
self.planetSpeed = TKPlanetSpeed;
self.physicsBody.velocity = CGVectorMake(0, self.planetSpeed);
}
//#param position: the point of planet on the screen
-(void)moveTowardsPosition:(CGPoint)position
{
float offScreenX = position.x;
float offScreenY = position.y - 2000;
CGPoint pointOffScreen = CGPointMake(offScreenX, offScreenY);
float Distance = pointOffScreen.y - position.y;
float time = Distance / self.planetSpeed;
SKAction *movePlanet = [SKAction moveTo:pointOffScreen duration:time];
NSArray *sequence = #[movePlanet, [SKAction removeFromParent]];
[self runAction:[SKAction sequence:sequence]];
}
The default value of friction is 0.2. So you can try:
self.physicsBody.friction = 0.0
now it won't be affected by surface anymore.

Animate Sprite Vertically

I am having real trouble getting a sprite to spawn on the screen at the top and then animate it from the top to the bottom. I have been following Ray Wenderlich’s tutorial on creating a simple game however that moves the sprite from right to left, I would like it to move from top to bottom and now I’m tremendously stuck! Below is my current code:
- (void)addComet:(CCTime)dt
{
// Make sprite
CCSprite *comet = [CCSprite spriteWithImageNamed:#"PlayerSprite.png"];
// Verticle spawn range
int minY = comet.contentSize.width;
int maxY = self.contentSize.height - comet.contentSize.height / 2;
int rangeY = maxY - minY;
int randomY = (arc4random() % rangeY) + minY;
// Position comets slightly off the screen
comet.position = CGPointMake(self.contentSize.width + comet.contentSize.width, randomY);
[self addChild:comet];
// Duration range comets take to fly across screen
int minDuration = 2.0;
int maxDuration = 4.0;
int rangeDuration = maxDuration - minDuration;
int randomDuration = (arc4random() % rangeDuration) + minDuration;
// Give comet animation
CCAction *actionMove = [CCActionMoveTo actionWithDuration:randomDuration position:CGPointMake(0, 500)];
CCAction *actionRemove = [CCActionRemove action];
[comet runAction:[CCActionSequence actionWithArray:#[actionMove,actionRemove]]];
}
If anyone could point me in the right direction because I’ve been stuck on this for quite a while and just cannot get the sprite to spawn randomly at the top of the screen and then animate down to the bottom. I have also looked at sample code such as tweejump but have had no luck.
Now, I haven't got Cocos2D in any of my projects, so don't know if there are any typos, but generally it should probably look a little something like the below. The idea is that all the comets should start at the same Y-position (off-screen) but have a randomized horizontal (x) position...
- (void)addComet:(CCTime)dt
{
// Make sprite
CCSprite *comet = [CCSprite spriteWithImageNamed:#"PlayerSprite.png"];
NSInteger y = self.contentSize.height; // perhaps + comet.contentSize.height / 2, if the anchorPoint is 0.5, 0.5
// Random horizontal position
NSInteger maxX = self.contentSize.width;
NSInteger randomX = (arc4random() % maxX);
// Position comets slightly off the screen
comet.position = CGPointMake(randomX, y);
[self addChild:comet];
// Duration range comets take to fly across screen
NSInteger minDuration = 2.0;
NSInteger maxDuration = 4.0;
NSInteger rangeDuration = maxDuration - minDuration;
NSInteger randomDuration = (arc4random() % rangeDuration) + minDuration;
// Give comet animation
CCAction *actionMove = [CCActionMoveTo actionWithDuration:randomDuration position:CGPointMake(randomX, 0)]; // Moving it in a straight line vertically
CCAction *actionRemove = [CCActionRemove action];
[comet runAction:[CCActionSequence actionWithArray:#[actionMove,actionRemove]]];
}

Set sprite using background position

I am new to cocos2d so please help me if u can
I have background moving from right to left, and the background contains small windows with 3 rows of windows
_spaceDust1 = [CCSprite spriteWithFile:#"bg_front_spacedust.png"];
_spaceDust2 = [CCSprite spriteWithFile:#"bg_front_spacedust.png"];
CGPoint dustSpeed = ccp(0.1 , 0.1);
CGPoint bgSpeed = ccp(0.05 , 0.05);
[_backgroundNode addChild:_spaceDust1 z:0 parallaxRatio:dustSpeed positionOffset:ccp(0,winSize.height / 2)];
[_backgroundNode addChild:_spaceDust2 z:0 parallaxRatio:dustSpeed positionOffset:ccp(_spaceDust1.contentSize.width , winSize.height / 2)];
Now add enemies wich also move from right to left with same speed
_robbers = [[CCArray alloc] initWithCapacity:kNumAstroids];
for (int i = 0; i < kNumAstroids; ++i) {
CCSprite *asteroid = [CCSprite spriteWithSpriteFrameName:#"robber.png"];
asteroid.visible = NO;
[_batchNode addChild:asteroid];
[_robbers addObject:asteroid];
}
in update method:
double curTime = CACurrentMediaTime();
if (curTime > _nextRunemanSpawn) {
float randSecs = [self randomValueBetween:0.20 andValue:1.0];
_nextRunemanSpawn = randSecs + curTime;
float randY = 80.0;
float randY1 = 185.0;
float randY2 = 293.0;
float randDuration = [self randomValueBetween:5.2 andValue:5.2];
float randDuration1 = [self randomValueBetween:1.0 andValue:1.0];
CCSprite *asteroid = [_robbers objectAtIndex:_nextRobber];
_nextRobber++;
if (_nextRobber >= _robbers.count) {
_nextRobber = 0;
}
//[asteroid stopAllActions];
int winChoice = arc4random() % 3;
if (winChoice == 0) {
asteroid.position = ccp(winSize.width +asteroid.contentSize.width / 2 , randY);
asteroid.visible = YES;
}
else if(winChoice == 1){
asteroid.position = ccp(winSize.width +asteroid.contentSize.width / 2 , randY1);
asteroid.visible = YES;
}else {
asteroid.position = ccp(winSize.width +asteroid.contentSize.width / 2 , randY2);
asteroid.visible = YES;
}
[asteroid runAction:[CCSequence actions:[CCMoveBy actionWithDuration:randDuration position:ccp(-winSize.width-asteroid.contentSize.width, 0)],
[CCCallFuncN actionWithTarget:self selector:#selector(setInvisible:)],nil]];
All is going well but i want to set this enemies in to window and in random position
so how can i set x-argument of enemies so it can be fix in to window of the background?
For some reason I cannot comment so this is written as an answer. What exactly are you trying to do? I am a bit confused. It sounds like you want the X position to be set so that it is in one of 3 random positions, is that correct?

Resources