# Spacesim character controller

Hello,

I have recently begun making a space simulator game, and have had trouble making a character controller that can be used by both the AI and the player. My previous controllers stored the target angle in a quaternion where the ship would gradually turn towards it until the angles match (For players this value would be adjusted using Input.GetAxis).

However, I had difficulty implementing angular acceleration as well as limiting the maximum turning rate of the ship. How would I go about making a controller with these features in JavaScript?

edit:

Here is my code that works properly, but i have had trouble adapting it for the AI. How could I make it work while keeping the same turning speed? Any suggestions are welcome.

`````` var targetAngleY:float = 0.0; //ship's yaw axis
var targetAngleX:float = 0.0; //ship's pitch axis
var targetAngleZ:float = 0.0; //ship's roll axis

var turnspeed:float = 0.25;

var inertiaFactor:float = 92.0;

function Update () {
Lookat();
}

function Lookat () {

if (transform.gameObject.tag == "Player") { //if player is piloting

targetAngleY += (Input.GetAxis("Horizontal")) * (turnspeed);
targetAngleX += (Input.GetAxis("Vertical")) * (turnspeed);
targetAngleZ += (Input.GetAxis("Roll")) * (turnspeed) ;

targetAngleY *= (inertiaFactor / 100);
targetAngleX *= (inertiaFactor / 100);
targetAngleZ *= (inertiaFactor / 100);

transform.Rotate(targetAngleX, targetAngleY, targetAngleZ);
}

else { //if AI is piloting

}
}
``````

function Lookat ()
{
Vector3 targetAngle;

`````` if (transform.gameObject.tag == "Player") { //if player is piloting

targetAngle.y = Input.GetAxis("Horizontal");
targetAngle.x = Input.GetAxis("Vertical");
targetAngle.z = Input.GetAxis("Roll");

}

else { //if AI is piloting

AISetsTargetAngle( targetAngle );

}

targetAngle *= turnspeed;

targetAngle *= (inertiaFactor / 100);   //why is this here?

transform.Rotate(targetAngle.x, targetAngle.y, targetAngle.z);
}
``````

Quaternion.LookRotation is returning your “End-goal” rotation and then we’re multiplying that by turn speed. On the other hand the player is giving 3 values between -1 & +1 which we multiply by turnspeed.

Off the top of my head, if you:

``````Quaternion LookRotation = Quaternion.LookRotation( targetPos - transform.position);

Vector3 temp = LookRotation.eulerAngles - transform.rotation.eulerangles;

for(int i = 0; i < 3; i++)  //Do this for all three values
{
if(temp _< -180)temp *+= 360;       //don't turn more than 180 degrees*_
``````

else if(temp > 180)temp -= 360;

temp = Mathf.Clamp( temp*, -1, 1); //AI output will be between -1 and +1*
}
This will give you a Vector3 with all of it’s values between -1 & +1 so you can muliply and use in transform.Rotate.
Thanks