Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- public class MoveCamera : MonoBehaviour
- {
- // Rotation speed in degrees per second
- public float rotationSpeed = 90f;
- // Minimum and maximum pitch angles
- public float minPitch = -80f;
- public float maxPitch = 80f;
- private float yaw = 0f; // Y-axis rotation
- private float pitch = 0f; // X-axis rotation
- // Movement speed in units per second
- public float moveSpeed = 5f;
- // Start is called once before the first execution of Update after the MonoBehaviour is created
- void Start()
- {
- // Initialize yaw and pitch from current rotation
- Vector3 euler = transform.rotation.eulerAngles;
- yaw = euler.y;
- pitch = euler.x;
- }
- // Update is called once per frame
- void Update()
- {
- // Get input from arrow keys
- float horizontal = 0f;
- float vertical = 0f;
- if (Input.GetKey(KeyCode.RightArrow))
- {
- horizontal = 1f;
- }
- else if (Input.GetKey(KeyCode.LeftArrow))
- {
- horizontal = -1f;
- }
- if (Input.GetKey(KeyCode.UpArrow))
- {
- vertical = 1f;
- }
- else if (Input.GetKey(KeyCode.DownArrow))
- {
- vertical = -1f;
- }
- // Calculate rotation deltas based on input and speed
- yaw += horizontal * rotationSpeed * Time.deltaTime;
- pitch -= vertical * rotationSpeed * Time.deltaTime; // Invert so up arrow looks up
- // Clamp pitch to prevent flipping
- pitch = Mathf.Clamp(pitch, minPitch, maxPitch);
- // Apply rotation
- transform.rotation = Quaternion.Euler(pitch, yaw, 0f);
- // Get movement input from WASD keys
- float moveForwardBack = 0f;
- if (Input.GetKey(KeyCode.W))
- {
- moveForwardBack = 1f;
- }
- else if (Input.GetKey(KeyCode.S))
- {
- moveForwardBack = -1f;
- }
- float moveLeftRight = 0f;
- if (Input.GetKey(KeyCode.D))
- {
- moveLeftRight = 1f;
- }
- else if (Input.GetKey(KeyCode.A))
- {
- moveLeftRight = -1f;
- }
- Vector3 forward = transform.forward;
- Vector3 right = transform.right;
- // Flatten forward and right to the horizontal plane (so no flying)
- forward.y = 0f;
- right.y = 0f;
- forward.Normalize();
- right.Normalize();
- Vector3 moveDirection = forward * moveForwardBack + right * moveLeftRight;
- // Normalize to prevent faster diagonal movement
- if (moveDirection.magnitude > 1f)
- {
- moveDirection.Normalize();
- }
- // Move the camera
- transform.position += moveDirection * moveSpeed * Time.deltaTime;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement