[Header("Camera Settings")]
public Transform playerCamera; // Reference to the camera transform
public float cameraSensitivity = 2f; // Sensitivity for camera rotation
private Rigidbody rb;
private float cameraPitch = 0f; // Vertical camera rotation
void Start()
{
rb = GetComponent<Rigidbody>();
if (rb == null)
{
Debug.LogError("No Rigidbody attached to the player.");
}
if (playerCamera == null)
{
Debug.LogError("Player camera not assigned.");
}
}
void Update()
{
var gamepad = Gamepad.current;
if (gamepad == null)
{
Debug.LogWarning("No gamepad connected.");
return;
}
// Read left stick input for horizontal movement
Vector2 leftStickInput = gamepad.leftStick.ReadValue();
if (leftStickInput.magnitude > 0.1f)
{
MovePlayer(leftStickInput);
}
// Read D-Pad vertical input for up and down movement
if (gamepad.dpad.up.wasPressedThisFrame)
{
MoveUpDown(1f);
}
else if (gamepad.dpad.down.wasPressedThisFrame)
{
MoveUpDown(-1f);
}
// Read right stick input for camera rotation
Vector2 rightStickInput = gamepad.rightStick.ReadValue();
if (rightStickInput.magnitude > 0.1f)
{
RotateCamera(rightStickInput);
}
}
void MovePlayer(Vector2 input)
{
// Fix reversed movement by inverting the input.y
Vector3 moveDirection = new Vector3(input.x, 0, input.y).normalized;
// Move relative to the camera's orientation
Vector3 cameraForward = playerCamera.forward;
cameraForward.y = 0f;
cameraForward.Normalize();
Vector3 cameraRight = playerCamera.right;
cameraRight.y = 0f;
cameraRight.Normalize();
Vector3 movement = (cameraForward * moveDirection.z + cameraRight * moveDirection.x) * moveSpeed;
// Apply force to move the player
rb.AddForce(movement, ForceMode.Acceleration);
// Clamp the player's horizontal speed to the max speed
Vector3 horizontalVelocity = new Vector3(rb.velocity.x, 0, rb.velocity.z);
if (horizontalVelocity.magnitude > maxSpeed)
{
Vector3 clampedVelocity = horizontalVelocity.normalized * maxSpeed;
rb.velocity = new Vector3(clampedVelocity.x, rb.velocity.y, clampedVelocity.z);
}
}
void MoveUpDown(float direction)
{
// Apply a strong impulse force to move up or down
Vector3 force = new Vector3(0, direction * dpadMoveForce, 0);
rb.AddForce(force, ForceMode.Impulse);
// Debug the vertical movement
Debug.Log($"Applied vertical force: {force}");
}
void RotateCamera(Vector2 input)
{
// Adjust sensitivity
float yaw = input.x * cameraSensitivity;
float pitch = -input.y * cameraSensitivity; // Invert Y-axis for natural feel
// Rotate the player object horizontally (yaw)
transform.Rotate(0f, yaw, 0f);
// Rotate the camera vertically (pitch)
cameraPitch += pitch;
cameraPitch = Mathf.Clamp(cameraPitch, -90f, 90f);
playerCamera.localEulerAngles = new Vector3(cameraPitch, 0f, 0f);
}