Camera moves jerkilily, problems a built game.

Hi everyone,

I’m creating my first videogame so I’m very new to this subject. I’m having problems with a camera script I made and I really don’t now how to fix it.

First of all here is the script:

/*
TO-DO:
*/
//Public vars
var walkSpeed = 5.0;
var runSpeed = 15.0;
var rotationSpeed = 0.1; //This is just a rotation speed coefficient
var gravity = 10.0;

//Private vars
private var isControllable = true;
//This var is called running instead of isRunning because of the presence of some APIs called isRunning
private var running = false;
//The final movement 3D vector
private var finalMovement = Vector3.zero;
//The final rotation 3D vector
//private var finalRotation = Vector3.zero;
//Where the player collides
private var moveCollisionFlags: CollisionFlags;
/*private var PreviousKeyboardX = 0.0;
private var PreviousKeyboardY = 0.0;
private var PreviousMouseX = 0.0;
private var PreviousMouseY = 0.0;*/

function Awake () {
}

function FixedUpdate () {
	//initialises the final movement and rotation 3D vectors
	finalMovement = Vector3.zero;
	//finalRotation = Vector3.zero;
	//This piece of code is to stun the player when necessary
	if (isControllable) {
		var KeyboardX = Input.GetAxisRaw("Horizontal");
		var KeyboardY = Input.GetAxisRaw("Vertical");
		var MouseX = Input.GetAxis("Mouse X");
		var MouseY = Input.GetAxis("Mouse Y");
		//If the player is giving commands regarding movement then move it
		if (Mathf.Abs(KeyboardX) >= 0.01 || Mathf.Abs(KeyboardY) >= 0.01) { 
			ApplyInputMovement(KeyboardX, KeyboardY);
		}
		ApplyGravityMovement();
		//This instruction is necessary to transform the finalMovement Direction from the local space
		//where the player's center is placed in (0, 0, 0) to the global space
		var finalGlobalMovement = transform.TransformDirection(finalMovement);
		GetComponent(CharacterController).Move(finalGlobal  Movement);
		if (Mathf.Abs(MouseX) >= 0.01) {
			//ApplyPlayerRotation(MouseX);
			transform.Rotate(0, MouseX * rotationSpeed, 0);
		}
	} else {
		Input.ResetInputAxes();
	}
}

function ApplyInputMovement (dX: float, dZ: float) {
	//dX: deltaX; dZ: deltaZ
	//Movement is not smoothed
	finalMovement.x = dX;
	finalMovement.z = dZ;
	finalMovement.Normalize();
	if (running) {
		finalMovement *= runSpeed;
	} else {
		finalMovement *= walkSpeed;
	}
	finalMovement *= Time.deltaTime;
}

function ApplyGravityMovement () {
	finalMovement.y = -gravity * Time.deltaTime;
}

function OnControllerColliderHit (hit : ControllerColliderHit ) {
	//Do something
}

//function isGrounded () {
//	return (collisionFlags  CollisionFlags.CollidedBelow) != 0;
//}

//function isMoving () : boolean { //Copied by default scripts
//	return Mathf.Abs(Input.GetAxisRaw("Vertical")) + Mathf.Abs(Input.GetAxisRaw("Horizontal")) > 0.5;
//}

function Reset () {//Copied by default scripts
	gameObject.tag = "Player";
}
// Require a character controller to be attached to the same game object
@script RequireComponent(CharacterController)
@script AddComponentMenu("Third Person Player/Custom TPS Controller")

And here is what I would like to obtain with my camera (In this game the camera can rotate looking to left, right, up and down but I only want the camera to be able to look left and right):

I didn’t cleaned the code yet so you’ll probably find unused vars. Sorry. I’m cleaning it now.
Ok, some of my problems came from the use of Time.deltaTime that I COMPLETELY removed from all my scripts (I truly don’t know how to use because it makes flicker everything, it isn’t really important but have you any suggestion?).
Today I tryed to build and run the game and I discovered an error that Unity never showed me. In Unity when I run my game everything goes really well or maybe it just hides the problem thanks to the reduced screen’s area used.
In the built game when I move the mouse in the “X direction” just a little (to test the minimum changement) the camera doesn’t rotate sharply like in that game but the camera has something similar to a discrete number of well defined steps.
To explain it more clearly it is like if the camera could rotate by 1.5°, 3°, 4.5° etc. but not 1.49°, 1.48°, 1.47° etc.
This is my first problem.
The other one is really weird for me that I’m not experienced with Unity.
In Unity the mouse X is read correctly and seems to work right. When I build the game and play it the mouse seems to be sometimes read and sometimes not. For example if I move the mouse with a costant velocity the game should rotate the camera linearly but what happens is that the camera doesn’t rotate for half a second and then it turns a lot. However the camera rotation is never the same even if I move the mouse always at the same velocity. I saw also that if I move the mouse to the right the camera rotates more than when I move the mouse to the left.

Can anyone help me solving my problems please?
Thank you,

BlackGecko

As far as the mouse is concerned, I don’t see where you are setting it in the script. Is there another script that controls the camera seperately?

For your X movement. I see where you have commented out:

private var PreviousMouseX = 0.0;

You would want to use it in your Fixed Update

		if(PreviousMouseX==0.0)PreviousMouseX=MouseX;
		//ApplyPlayerRotation(MouseX);
		transform.Rotate(0, (MouseX - PreviousMouseX)  * rotationSpeed, 0);
		PreviousMouseX=MouseX;

As far as the Time.deltaTime, this is not applicable in the FixedUpdate as it has a static time it is supposed to run (every 0.02 seconds) It would be more valuable in the Update function or something else.

I actually don’t ordinarily use the FixedUpdate function as if you do can’t complete it within that cycle it will bog down your game.

If your Camera is parented to your game object, you may find that any jerky that your player does, will happen to your camera as well. :wink:

Thank you very much.

Here is the cleaned out code (CustomTPSController):

//Public vars
var walkSpeed = 5.0;
var runSpeed = 15.0;
var rotationSpeed = 0.1; //This is just a rotation speed coefficient
var gravity = 10.0;

//Private vars
private var isControllable = true;
//This var is called running instead of isRunning because of the presence of some APIs called isRunning
private var running = false;
//The final movement 3D vector
private var finalMovement = Vector3.zero;
//Where the player collides
private var moveCollisionFlags: CollisionFlags;

function FixedUpdate () {
	//initialises the final movement and rotation 3D vectors
	finalMovement = Vector3.zero;
	//This piece of code is to stun the player when necessary
	if (isControllable) {
		var KeyboardX = Input.GetAxisRaw("Horizontal");
		var KeyboardY = Input.GetAxisRaw("Vertical");
		var MouseX = Input.GetAxis("Mouse X");
		var MouseY = Input.GetAxis("Mouse Y");
		//If the player is giving commands regarding movement then move it
		if (Mathf.Abs(KeyboardX) >= 0.01 || Mathf.Abs(KeyboardY) >= 0.01) { 
			ApplyInputMovement(KeyboardX, KeyboardY);
		}
		ApplyGravityMovement();
		//This instruction is necessary to transform the finalMovement Direction from the local space
		//where the player's center is placed in (0, 0, 0) to the global space
		var finalGlobalMovement = transform.TransformDirection(finalMovement);
		GetComponent(CharacterController).Move(finalGlobalMovement);
		if (Mathf.Abs(MouseX) >= 0.01) {
			transform.Rotate(0, MouseX * rotationSpeed, 0);
		}
	} else {
		Input.ResetInputAxes();
	}
}

function ApplyInputMovement (dX: float, dZ: float) {
	//dX: deltaX; dZ: deltaZ
	//Movement is not smoothed
	finalMovement.x = dX;
	finalMovement.z = dZ;
	finalMovement.Normalize();
	if (running) {
		finalMovement *= runSpeed;
	} else {
		finalMovement *= walkSpeed;
	}
	finalMovement *= Time.deltaTime;
}

function ApplyGravityMovement () {
	finalMovement.y = -gravity * Time.deltaTime;
}

function OnControllerColliderHit (hit : ControllerColliderHit ) {
	//Do something
}

function Reset () {//Copied by default scripts
	gameObject.tag = "Player";
}
// Require a character controller to be attached to the same game object
@script RequireComponent(CharacterController)
@script AddComponentMenu("Third Person Player/Custom TPS Controller")

The purpose is to move the player and considering that the movement on mouse X affects the player it is handled here.

The other script is the one that gives the rotation and the position to the camera (CustomTPSCamera):

//The main camera transform
private var mainCamera : Transform;
//The GameObject transform
private var _target : Transform;
//The camera's distance from the center of the character controller on the X axis
var xOffset = 1.5;
//The camera's distance from the center of the character controller on the Y axis
var yOffset = 1.5;
//The camera's distance from the center of the character controller on the Z axis
var zOffset = 7.5;
//The distance between the GameObject's center and the collider center
private var centerOffset = Vector3.zero;
//The distance between the GameObject's center and the collider's highest point
private var headOffset = Vector3.zero;

function Awake () {
	if(!mainCamera  Camera.main)
		mainCamera = Camera.main.transform;
	if(!mainCamera) {
		Debug.Log("mainCamera is not setted. Give the \"Main Camera\" tag to a camera.");
		enabled = false;	
	}
	
	_target = transform;
	if (_target) {
		controller = _target.GetComponent(CustomTPSController);
	}
	
	if (controller) {
		var characterController : CharacterController = _target.collider; //This takes the capsule collider reference
		centerOffset = characterController.bounds.center - _target.position; //This takes the distance between the GameObject's center and the collider center
		headOffset = centerOffset;
		headOffset.y = characterController.bounds.max.y - _target.position.y; //This takes the distance between the GameObject's center and the collider's highest point
	}
	else {
		Debug.Log("\"CustomTPSController\" script is not attached. Attach it to make the camera work.");
		enabled = false;
	}
	//MODIFIED: Cut(_target, centerOffset);
}

function Update () { //Note added for Unity Forum: if I use FixedUpdate I have the usual problem of the camera moving jerkily
	mainCamera.position = transform.TransformPoint(Vector3(xOffset, yOffset, -zOffset));
	mainCamera.rotation = transform.rotation;
}

I used FixedUpdate to solve a problem that is really making me go crazy… every translation and every rotation introduces a “jerk effect”. I didn’t know that FixedUpdate() was “dangerous” to use so know I’m going to use only Update(). What do you suggest me to finally solve the problem of what I call the “jerk effect”? This would solve my worst problem. I’m trying to figure it out analyzing other scripts but I still can’t really understand it.

Thank you again.

you may find that it will work better using Update instead of FixedUpdate as this is done at each rendered frame so will will react to the framerate better.

A spring camera detached from being parented to the character, but moving with it, also the step that the rotation will be compared to rate inwhich the mouse will send out mickys( yes thats right mickys ) the units of mouse movement. will be different, changing a goal rotation and then rotating towards that each frame using Time.deltaTime will make it much smoother.

Ok… time to start over…

Directly from the MouseOrbit.js (standard assets)

var target : Transform;
var distance = 10.0;

var xSpeed = 250.0;
var ySpeed = 120.0;

var yMinLimit = -20;
var yMaxLimit = 80;

private var x = 0.0;
private var y = 0.0;

@script AddComponentMenu("Camera-Control/Mouse Orbit")

function Start () {
    var angles = transform.eulerAngles;
    x = angles.y;
    y = angles.x;

	// Make the rigid body not change rotation
   	if (rigidbody)
		rigidbody.freezeRotation = true;
}

function LateUpdate () {
    if (target) {
        x += Input.GetAxis("Mouse X") * xSpeed * 0.02;
        y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02;
 		
 		y = ClampAngle(y, yMinLimit, yMaxLimit);
 		       
        var rotation = Quaternion.Euler(y, x, 0);
        var position = rotation * Vector3(0.0, 0.0, -distance) + target.position;
        
        transform.rotation = rotation;
        transform.position = position;
		
[B]		var lookAtPos=target.position - transform.position;
		lookAtPos.y=0;
		lookAtPos.Normalize();
		lookAtPos=target.position + lookAtPos;
		target.LookAt(lookAtPos);[/B]
    }
}

static function ClampAngle (angle : float, min : float, max : float) {
	if (angle < -360)
		angle += 360;
	if (angle > 360)
		angle -= 360;
	return Mathf.Clamp (angle, min, max);
}

I added some code to it to make the target face away (or possibly towards) the camera but stay upright.

I know it probably isnt exactly what you are looking for, but I think it would do good.

Thank you very much BigMisterB for the script and for the modifies. I’ll study the script and if necessary I’ll modify it. Anyway before attempting to modify anything I’ll try to understand and learn everything I can. I really like making videogames so It’s my target to learn as much as I can. Thank you too AJ.

Hi all,

I modified the script in order to work as I needed. I just commented the parts that were unnecessary to me so the script will be easier to understand to the people that will find it =). Thank you again.

var target : Transform;
var cameraDistance = 9.0;
var cameraHeight = 3.0;

var xSpeed = 250.0;
//var ySpeed = 120.0;

//var yMinLimit = -20;
//var yMaxLimit = 80;

private var x = 0.0;
private var y = 0.0;

//@script AddComponentMenu("Camera-Control/Mouse Orbit")

function Start () {
    var angles = transform.eulerAngles;
    x = angles.y;
    y = angles.x;

	// Make the rigid body not change rotation
   	if (rigidbody)
		rigidbody.freezeRotation = true;
}

function LateUpdate () {
    if (target) {
        x += Input.GetAxis("Mouse X") * xSpeed * 0.02;
        //y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02;
 		
 		//y = ClampAngle(y, yMinLimit, yMaxLimit);
 		       
        var rotation = Quaternion.Euler(0, x, 0); //Modified
        var position = rotation * Vector3(0.0, cameraHeight, -cameraDistance) + target.position;
        
        transform.rotation = rotation;
        transform.position = position;
		
		var lookAtPos=target.position - transform.position;
		lookAtPos.y=0;
		lookAtPos.Normalize();
		lookAtPos=target.position + lookAtPos;
		target.LookAt(lookAtPos);
    }
}

/*static function ClampAngle (angle : float, min : float, max : float) {
	if (angle < -360)
		angle += 360;
	if (angle > 360)
		angle -= 360;
	return Mathf.Clamp (angle, min, max);
}*/

I forgot to add the solution to my problem…
Here is how I solved it. I noticed that BigMisterB was using the LateUpdate on the camera instead of the Update.
After that I searched and found this: http://unity3d.com/support/documentation/Manual/Update%20Order.html

My problem is just as confusing. I have been trying for ages now but I just can’t figure this out…

When I move forward or sideways, everything is fine. As soon as I press down and my character moves towards the camera, it jitters like an earthquake… Will post some code later on. I would greatly appreciate any assistance on this.

Hi,

do the script attached to the camera use LateUpdate() instead of Update()?