Reputation: 364
I tried to make a box of balls where the balls move with constant velocity. The shouldn't slow down when they collide with each other. I think I have set all properties right but it didn't work and after 30s all of the balls stopped to move.
The box is set like this:
self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
self.physicsBody.dynamic = false
self.physicsBody.restitution = 1
self.physicsBody.friction = 0
The balls are set like this:
Is this a bug of the physics engine or am I missing something?
Upvotes: 4
Views: 3084
Reputation: 20274
In addition to Steffen's (LearnCocos2D) answer, the methods mentioned in the pseudo-code can be found in this very good Ray Wenderlich tutorial.
static inline CGPoint rwAdd(CGPoint a, CGPoint b) {
return CGPointMake(a.x + b.x, a.y + b.y);
}
static inline CGPoint rwSub(CGPoint a, CGPoint b) {
return CGPointMake(a.x - b.x, a.y - b.y);
}
static inline CGPoint rwMult(CGPoint a, float b) {
return CGPointMake(a.x * b, a.y * b);
}
static inline float rwLength(CGPoint a) {
return sqrtf(a.x * a.x + a.y * a.y);
}
// Makes a vector have a length of 1
static inline CGPoint rwNormalize(CGPoint a) {
float length = rwLength(a);
return CGPointMake(a.x / length, a.y / length);
}
They use CGPoint
as the parameters and return value, but this can be easily converted to use CGVector
.
These methods are very useful for physics calculations, and you will find use for them at many points. It is best to keep these methods in a separate header file, and use them in the code throughout your project.
Upvotes: 2
Reputation: 64478
If you want them to have a constant velocity all the time, no change at all, you're going to have to set their velocity to a fixed-length vector in SKScene update. Physics engines aren't designed to adhere strictly to the conservation of energy law ... or one could argue that some energy is dissipated through heating the device. ;)
General principle for keeping the same direction but adjusting vector length/speed to a fixed value (pseudo-code):
CGPoint velocity = somePhysicsBody.velocity;
velocity = normalized(velocity);
velocity = multiply(velocity, desiredSpeed);
somePhysicsBody.velocity = velocity;
Upvotes: 4