Face the direction that i'm moving in (2D movement)

Hi,

I’m fiddling around a bit with the scripts from the 2D platformer. I found the PlatformerController script to be quite big for what i wanted to do (basically just learn about various components etc). And this is what i go so far.

var speed = 6.0;
var jumpSpeed = 8.0;
var gravity = 20.0;

private var moveDirection = Vector3.zero;
private var rotationSmoothing = 0.1;

function FixedUpdate() {
	var controller : CharacterController = GetComponent(CharacterController);
	if (controller.isGrounded) {
		// We are grounded, so recalculate
		// move direction directly from axes
		moveDirection = Vector3(Input.GetAxis("Horizontal"), 0,0);
		moveDirection = transform.TransformDirection(moveDirection);
		moveDirection *= speed;

		if (Input.GetButton ("Jump")) {
			moveDirection.y = jumpSpeed;
		}
	}
	
        // Apply gravity
	moveDirection.y -= gravity * Time.deltaTime;

	// Move the controller
	controller.Move(moveDirection * Time.deltaTime);
}

Now i want to rotate my characterController in the direction that i’m moving in using a piece from the 2d platformer script. But when i add this in, my character starts spinning around like crazy.

if (moveDirection.sqrMagnitude > 0.01)
		transform.rotation = Quaternion.Slerp (transform.rotation, Quaternion.LookRotation (moveDirection), Time.deltaTime * rotationSmoothing);

Could someone explain to me exactly what happens in this script and where i go wrong? Or atleast point me in the direction where i can gain better understanding.

Thanks!

Maybe use transform.eulerAngles instead of transform.rotation?

the link:

something like:

if (moveDirection.sqrMagnitude > 0.01)
      transform.eulerAngles.y = 180;

with some adaptations to smooth the move :slight_smile:

and I can’t explain you Quaternion angles because… I don’t understand them quite exactly myself :lol:

Thanks for the reply. Doesn´t see, to work though since it get´s called several times, making the cube not rotate at all.

Right now i´m trying to make heads-tails from the 2d platformer script but there just is so much physics in it that i don´t need/fathom right now.

I just want to make, let’s say, a cube face the way in which it moves.

transform.LookAt(transform.position + rigidbody.velocity.normalized);

You’ll need to be using rigidbody velocities to use the above, but the same principle applies so long as you have a velocity vector you can use.