0
votes

I've got a body that has to rotate on touch. There is no linear movement needed, they body just needs to rotate along an axis point.

I'm using setTransform to rotate the body in the onAreaTouched event. Like this:

body.setTransform(body.getPosition(),((float)Math.atan2(-(pSceneTouchEvent.getX() - startX), (pSceneTouchEvent.getY() - startY)))); 

This is done in the 'Move' Action. StartX and StartY denote the starting X and Y points. They are reset after the above line of code, as:

startX = pSceneTouchEvent.getX();
startY = pSceneTouchEvent.getY();

The code does rotate the body BUT the body jitters while rotating if the speed of touch movement is slow. With faster movement of touch the body rotates smoothly.

How can I make the body rotation smooth (Whether the touch movement is slow of fast)?

1

1 Answers

0
votes

Use the touch event to set a target angle. Then use the onUpdate to ease toward the target angle.

This is a snippet of code that eases your rotation towards a point. I this may have errors, as I just typed it in the box here, but you should be able to see my methodology. As an added bonus, the Math.atan() stuff will make sure it always turns towards the shortest direction of the touch event skips around a bit:

// SET THIS IN YOUR TOUCH EVENT
// Rotate towards Touch.
Float RADIANS_TO_DEGREES = 57.2957795;
Float DEGREES_TO_RADIANS = 0.0174532925;
Float EASE_AMOUNT = 0.05;
PointF p = new PointF(body.x, body.y); // Save this as instance var so it persists.
p.x -= pSceneTouchEvent.getX();
p.y -= pSceneTouchEvent.getX();

// THIS PART GOES IN THE ON UPDATE
Float originalrotation = body.getRotation() * DEGREES_TO_RADIANS;
Float targetrotation = Math.atan2(p.y, p.x);
Float rotationdifference = Math.atan2(Math.sin(targetrotation-originalrotation),Math.cos(targetrotation-originalrotation));

// To ease, we apply only a percentage of the rotation needed.
circle.rotation += rotationdifference*RADIANS_TO_DEGREES* EASE_AMOUNT;