gpt-4o-2024-11-20· openai
from WildChat-4.8M
Write me a C# Unity script that allows me to use wsad to fly the camera around and shift…
- User
Write me a C# Unity script that allows me to use wsad to fly the camera around and shift to boost the speed.
- Assistant
Here's a C# script that allows you to control the camera using WSAD keys, with shift to boost the movement speed. Attach this script to the GameObject that has your
Cameracomponent in Unity.csharpusing UnityEngine; public class CameraFly : MonoBehaviour { public float normalSpeed = 10f; // Normal movement speed public float boostMultiplier = 2f; // Multiplier for boost speed public float rotationSpeed = 100f; // Speed for mouse-based rotation private float currentSpeed; void Update() { HandleMovement(); HandleRotation(); } void HandleMovement() { // Get input for forward, backward, left, and right float moveX = Input.GetAxis("Horizontal"); // A/D keys or Left/Right Arrow keys float moveZ = Input.GetAxis("Vertical"); // W/S keys or Up/Down Arrow keys // Check if Shift is held down for boosting currentSpeed = Input.GetKey(KeyCode.LeftShift) ? normalSpeed * boostMultiplier : normalSpeed; // Compute movement direction based on input Vector3 movement = (transform.right * moveX + transform.forward * moveZ) * currentSpeed * Time.deltaTime; // Apply translation to the camera transform.Translate(movement, Space.World); } void HandleRotation() { // Check if the right mouse button is held down if (Input.GetMouseButton(1)) { // Get mouse input for the X and Y axis float mouseX = Input.GetAxis("Mouse X"); float mouseY = Input.GetAxis("Mouse Y"); // Rotate the camera around the Y-axis (horizontal movement) and X-axis (vertical movement) transform.Rotate(Vector3.up, mouseX * rotationSpeed * Time.deltaTime, Space.World); transform.Rotate(Vector3.left, mouseY * rotationSpeed * Time.deltaTime); } } }