- Home /
Slow rigidbody movement in all directions but forward.
Hi, I have a short script that controls a spacecraft. I have two issues with it. Firstly the rotation doesn't change speed if I increase or decrease the MaxRotSpeed variable even though it is being calculated with it. Secondly I have no idea how I am going to slowly cease all movement in every direction other than the one I want to go in. At the moment if I turn while flying the velocity doesn't decrease as I move in a new direction except if move in the actively oppose it by flying in the exact opposite direction. At the moment all I am doing is adding speed in my new direction and keeping the speed in my old direction. Here is my full script: public class PlayerControlScript : MonoBehaviour {
public float maxMovSpeed = 5.0f; // Maximum speed set by the engine component
public float curMovSpeed = 0.0f; // Current speed set by the player increasing of decreasing the throttle
public float accSpeed = 0.1f; // Speed at which the movSpeed can increase or decrease
public float maxRotSpeed = 5.0f; // Maximum speed at which the craft can rotate
public float brakePower = 0.97f; // How quickly the brake affects the craft
void FixedUpdate() {
// Yaw, Pitch and roll
float h = Input.GetAxis("Mouse X"); // Yaw
float v = Input.GetAxis("Mouse Y"); // Pitch
float roll = Input.GetAxis("Roll"); // Roll
rigidbody.AddRelativeTorque(-v * maxRotSpeed, h * maxRotSpeed, roll * maxRotSpeed); // Use the 3 rotations in a vector that is multiplied by the max roll speed and added relatively to the rigidbody as torque
// Accellerate
// If the forward button is pressed add speed to move speed var
if (Input.GetAxis("Forward") > 0.0f && curMovSpeed < maxMovSpeed) {
curMovSpeed += accSpeed;
}
// Deccellerate
// If the backward button is pressed remove speed from move speed var
if (Input.GetAxis("Forward") < 0.0f && curMovSpeed > -maxMovSpeed){
curMovSpeed -= accSpeed;
}
rigidbody.AddForce(transform.forward * curMovSpeed); // Add move speed var to rigidbody as force in forward direction
// If the left or right buttons are pressed add lateral force accordingly
if (Input.GetAxis ("Right") > 0.0f || Input.GetAxis ("Right") < 0.0f) {
rigidbody.AddForce(transform.right * (curMovSpeed / 2) * Input.GetAxis ("Right"));
}
// If the brake button is pressed slow to a stop in all directions
if (Input.GetAxis ("Brake") > 0.0f)
{
rigidbody.velocity = rigidbody.velocity * brakePower;
}
}
}
Comment