-1

I wanted to create a bouncy box. Something like a jelly, where anything that hits it will also bounce. I tried physicsBody.restitution but it doesn't work because it seems to be the bounciness of an object if it hits another object. But what I want is the bounciness if it gets hit by an object.

Was looking through the docs and didn't find anything. Anyone has any idea on making something like this?

I currently have a ball and a block (pong game) for practice, I want the ball to bounce a little faster each time it hits a block. So I added a restitution of 1.02 to the ball. Is that right?

_ball.physicsBody = [SKPhysicsBody bodyWithPolygonFromPath:ballPath];
_ball.physicsBody.friction       = 0.f;
_ball.physicsBody.restitution    = 1.02f;
_ball.physicsBody.linearDamping  = 0.f;
_ball.physicsBody.allowsRotation = NO;
_ball.physicsBody.affectedByGravity = NO;

I also have blocks that are supposed to be hit by the ball and these blocks are jelly so it should bounce harder, but adding restitution to it doesn't change anything on the scene.

_block.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:_block.size];
_block.physicsBody.friction = 0.f;
_block.physicsBody.restitution = 0.f;
majidarif
  • 18,694
  • 16
  • 88
  • 133

1 Answers1

0

Restitution

Setting the restitution to 1.02 will not work. Apple documentation states:

The property must be a value between 0.0 and 1.0. The default value is 0.2.

To increase the velocity of an object, just get the zRotation of the node and apply a small impulse in that direction. The impulse is a CGVector, here is some useful code for converting angles into CGVectors.

[ball.physicsBody applyImpulse:impulse];

Jelly

As for the jelly effect, I would recommend looking into SKTUtils categories provided by Ray Wenderlich. The example project demonstrates several effects similar to your needs.

The code provides plenty new timing functions than SpriteKit currently supports, such as elastic, cubic and bounce. Think of applying an elastic scaling function to the 'jelly'-object after a collision.

#import "SKNode+SKTExtras.h"
#import "SKTEffects.h"

SKTScaleEffect *scaleEffect = [SKTScaleEffect effectWithNode:node duration:0.25f startScale:1.5f endScale:1.5f];
scaleEffect.timingFunction = SKTTimingFunctionElasticEaseOut;
[node runAction:[SKAction actionWithEffect:scaleEffect]];

Data encapsulation

Also, don't use _ball but self.ball: this ensures the corresponding getters/setters are called. According to Apple docs:

In general, you should use accessor methods or dot syntax for property access even if you’re accessing an object’s properties from within its own implementation, in which case you should use self. (...) The exception to this rule is when writing initialization, deallocation or custom accessor methods, as described later in this section.

Community
  • 1
  • 1
CloakedEddy
  • 1,965
  • 15
  • 27