Hi Everyone!
I'm working on a 2D side scrolling car game using a car composite.
When the player presses the left or right arrow keys, the car needs to flip around to point in the correct direction.
Can anyone suggest the best (simplest!) way to do this?
Thanks!
Probably just flip the sprite and then invert the controls?
@liabru My custom car composite isn't symmetrical. It looks a bit like this:
http://piqnt.com/planck.js/Car
So I would need at least to flip the body around.
Also, I'd like to maintain the car's momentum when it changes direction, so that, for example, if it's travelling to the left, and then flips to the right, it still maintains it's current speed, but in its new direction.
There might be a few different systems at play here, but the first thing I would need to do is invert the orientation of the composite, which I haven't yet figured out how to do.
You could try scaling the body like this Body.scale(body, -1, 1) but be aware this might have a few issues see #443?
@liabru Amazing, that just works! Thank you! 馃槃
Here's the code I'm using that does the trick:
let carBody = car.bodies[0],
leftWheel = car.bodies[1],
rightWheel = car.bodies[2];
Body.scale(carBody, -1, 1);
carBodySprite.scale.x = -carBodySprite.scale.x;
Body.setAngularVelocity(leftWheel, -leftWheel.angularVelocity);
Body.setAngularVelocity(rightWheel, -rightWheel.angularVelocity);
carPower = -carPower;
It's a very natural looking effect.
@liabru Oh no!
More testing uncovered an unexpected side-effect.
My car starts off life like this:

If it hits a wall, its rotation changes as it bumps against the wall surface.
But, if the user inverts the car's scale by pressing the the "left" button at the same time as its rotation changes, the car body's current rotation is locked into the composite:

Eventually, if its scale changes enough times while it's rotating, the car looks something like this:

So my next question is:
"Is there a way to normalize the rotation of the body to 0 Radians before scaling it?"
(It seems Body.rotate is only used to set a relative angle - how could I set an absolute angle? Or, and am I just thinking about the problem in the wrong way?)
@liabru Solved!
I used setAngle to set the carBody to 0 Radians before inverting the scale:
Body.setAngle(carBody, 0);
Body.scale(carBody, -1, 1);
Most helpful comment
@liabru Solved!
I used
setAngleto set thecarBodyto 0 Radians before inverting the scale: