so I Created a basic camera controller and a floor to walk around on, I added coliders to the camera and to the floor, and have a gravity function to pull the camera down to the floor.
I am successfully capturing WASD commands and moving the camera based on that,
I am also successfully capturing mouse movement and panning the camera based on that.
The issue i’m encountering is, when my camera is angled towards the floor, and I hold W then my camera will move in a striaght line in the direction its facing through the floor.
The other issue i’m encountering is I need to add a maximum rotation value to my camera, becuase if the user rotates it upside down then the gravity function is no longer true, and it falls into the sky.
here is my camera controller code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour
{
public float moveSpeed = 5.0f;
public float rotationSpeed = 2000.0f;
public float gravity = 9.81f; // Gravity force
public float groundCheckDistance = 2f;
private float verticalVelocity = 0.0f; // Gravity's vertical effect
private bool isGrounded;
public LayerMask groundLayer;
void ApplyGravity()
{
// Check if the camera is grounded
isGrounded = Physics.Raycast(transform.position, transform.TransformDirection(Vector3.down), groundCheckDistance, groundLayer);
if (isGrounded)
{
verticalVelocity = 0; // Reset gravity when on the ground
}
else
{
// Apply gravity when not grounded
verticalVelocity -= gravity * Time.deltaTime;
}
// Move the camera down based on gravity
transform.Translate(Vector3.up * verticalVelocity * Time.deltaTime);
}
void Update()
{
Camera camera = GetComponent<Camera>();
// Handle movement with WASD
if(isGrounded){
// Handle movement with WASD
float moveX = Input.GetAxis("Horizontal") * moveSpeed * Time.deltaTime; // A/D or left/right arrow
float moveZ = Input.GetAxis("Vertical") * moveSpeed * Time.deltaTime; // W/S or up/down arrow
// Create a global movement vector
Vector3 move = new Vector3(moveX, 0, moveZ);
// Move the camera globally
camera.transform.Translate(move);
}
ApplyGravity();
float rotationX = Input.GetAxis("Mouse X") * rotationSpeed * Time.deltaTime;
float rotationY = -Input.GetAxis("Mouse Y") * rotationSpeed * Time.deltaTime;
// Rotate around the global Y axis
camera.transform.Rotate(0, rotationX, 0, Space.World);
// Rotate around the local X axis (for looking up/down)
camera.transform.Rotate(rotationY, 0, 0);
if (Input.GetKeyDown(KeyCode.Space)){
}
}
}
here is a screen shot of how i have attached the collider to the camera:
here is a screen shot how how i have configured the collider for the floor:
Many thanks in advance