Untitled
unknown
plain_text
a year ago
3.2 kB
7
Indexable
using UnityEngine; public class Spaceship0 : MonoBehaviour { public float thrustForce = 10f; // Force applied for acceleration public float rotationSpeed = 100f; // Speed of rotation for pitch and yaw public float rollSpeed = 100f; // Speed of roll (rotation around the local Z-axis) public float maxSpeed = 20f; // Maximum allowed speed public float dragWhenIdle = 5f; // Drag applied when not accelerating public float rollDamping = 0.1f; // Damping factor for roll rotation public KeyCode stopRotationKey = KeyCode.R; // Key to stop all rotation private Rigidbody rb; void Start() { // Get the Rigidbody component attached to the spaceship rb = GetComponent<Rigidbody>(); } void Update() { // Check if the stop rotation key is pressed if (Input.GetKey(stopRotationKey)) { // Stop all rotation rb.angularVelocity = Vector3.zero; return; // Skip the rest of the Update method } // Get input for rotation float pitchInput = Input.GetAxis("Vertical"); // W = 1, S = -1 for pitch float yawInput = Input.GetAxis("Horizontal"); // A = -1, D = 1 for yaw float rollInput = 0f; // Roll input for Q and E keys if (Input.GetKey(KeyCode.Q)) { rollInput = rollSpeed * Time.deltaTime; // Roll left (counterclockwise) } else if (Input.GetKey(KeyCode.E)) { rollInput = -rollSpeed * Time.deltaTime; // Roll right (clockwise) } // Calculate rotations in world space for pitch and yaw Vector3 pitchRotation = Vector3.right * pitchInput * rotationSpeed * Time.deltaTime; Vector3 yawRotation = Vector3.up * yawInput * rotationSpeed * Time.deltaTime; // Apply pitch and yaw rotations in world space Quaternion targetRotation = Quaternion.Euler(pitchRotation + yawRotation); rb.MoveRotation(targetRotation * rb.rotation); // Apply roll rotation around the local Z-axis with damping Vector3 rollTorque = Vector3.forward * rollInput; rb.AddRelativeTorque(rollTorque); // Dampen roll if not actively rolling if (rollInput == 0f) { rb.angularVelocity = new Vector3( rb.angularVelocity.x, rb.angularVelocity.y, Mathf.Lerp(rb.angularVelocity.z, 0f, rollDamping * Time.deltaTime) ); } // Check for acceleration input (Shift key) if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) { // Calculate forward thrust Vector3 thrust = transform.forward * thrustForce; // Apply thrust to the spaceship rb.AddForce(thrust); // Clamp the spaceship's velocity to the maximum speed rb.velocity = Vector3.ClampMagnitude(rb.velocity, maxSpeed); // Reset drag to 0 for normal thrust rb.drag = 0; } else { // Apply drag when not accelerating rb.drag = dragWhenIdle; } } }
Editor is loading...
Leave a Comment