Rotating my character only while moving in a 2D plane

Hi everyone. I’ve spent about 6 hours now trying to figure this out… I’ve tried so many different versions of code and nothing seems to work. I’m creating a 2D side scroller and when my character moves I want him to rotate around. Think of sonic the hedgehog when sonic spins and rolls. Or even just think of a sphere that rotates in the direction you move it. I want my character to spin at a very fast rate. I’ve tried adjusting torque and force to my rigidbody over every axis and all that does is make him very choppy; it does not affect his rotation at all. I’m doing something wrong wrong and reaching out in hopes someone might be able to lend a hand. Anyone have any solutions, code snippets or tips using Java?

You should use the actual velocity to calculate the rotation, and use transform.Rotate to make it spin. If your character is a rigidbody, you can use:

var factor = 120; // degrees per meter

function FixedUpdate(){
  var angle = rigidbody.velocity.x * Time.deltaTime * factor;
  transform.Rotate(0, 0, angle);

This will rotate the character in the direction it’s moving in the X axis (invert angle sign if it spins to the wrong side). You can adjust factor to get the spinning velocity you want.

NOTE: Set rigidbody.freezeRotation=true at Start to avoid interference from physics rotational effects.

EDITED: Well, since you’re using a CharacterController, things must be somewhat different: you must child your model to the character object and rotate it proportionally to the distance travelled each Update (model script):

var speed: float = 120;
private var lastPos: Vector3;

function Update(){
  var dist = transform.position - lastPos;
  lastPos = transform.position;
  var angle = dist.x * speed;
  transform.Rotate(0, 0, angle);

fyi what aldonaletto wrote works correctly for anyone trying to do this w/ a character controller. Just make sure you adjust the rotate smoothing to 0 and the speed smoothing to a small value (I set it to 0.2) The roll effect works like a charm! :slight_smile: Thanks again!

The best solution may be to separate the visual representation from the physics representation. Keep the rigidbody and collider as they are, but have the visible mesh be a component of a child object, then use transform.Rotate on it.