Virtual Reality Space Explorer Unity, C#
👤 Sharing: AI
```csharp
using UnityEngine;
public class SpaceExplorer : MonoBehaviour
{
// Movement Speed
public float moveSpeed = 5f;
// Rotation Speed
public float rotationSpeed = 2f;
// A reference to the camera. Ideally, assign this in the inspector.
public Camera vrCamera;
// Rigidbody for collision and physics interactions. Must be on the same GameObject.
private Rigidbody rb;
void Start()
{
// Get the Rigidbody component attached to this GameObject.
rb = GetComponent<Rigidbody>();
// Ensure the Rigidbody is properly configured for VR interaction.
if (rb == null)
{
Debug.LogError("Rigidbody component not found! Add a Rigidbody component to this GameObject.");
enabled = false; // Disable the script if no Rigidbody is found.
return;
}
rb.freezeRotation = true; //Important: Prevent external forces from rotating the player, as VR rotation is handled separately.
rb.useGravity = false; // Typically, in space, there's no gravity. Can be changed if needed for a specific experience.
//Find the Camera if not manually assigned.
if (vrCamera == null)
{
vrCamera = GetComponentInChildren<Camera>(); //Assumes the camera is a child
if (vrCamera == null)
{
Debug.LogError("VR Camera not found! Assign the VR camera to the 'vrCamera' field in the Inspector, or ensure a Camera component is a child of this GameObject.");
enabled = false; // Disable the script if no VR camera is found.
return;
}
}
}
void Update()
{
HandleMovement();
HandleRotation();
}
void HandleMovement()
{
// Get input for forward/backward movement
float verticalInput = Input.GetAxis("Vertical"); // Typically bound to W/S or up/down arrow keys.
// Get input for strafing movement (left/right)
float horizontalInput = Input.GetAxis("Horizontal"); // Typically bound to A/D or left/right arrow keys.
//Calculate movement direction based on input and the *camera's* forward and right vectors.
//This makes movement relative to where the player is looking, not world space.
Vector3 moveDirection = vrCamera.transform.forward * verticalInput + vrCamera.transform.right * horizontalInput;
moveDirection.Normalize(); // Normalize to prevent faster movement when moving diagonally.
// Apply movement: Use Rigidbody.MovePosition for smooth, physics-based movement.
Vector3 newPosition = rb.position + moveDirection * moveSpeed * Time.deltaTime;
rb.MovePosition(newPosition);
}
void HandleRotation()
{
// Get input for horizontal rotation (yaw)
float horizontalRotation = Input.GetAxis("Mouse X"); // Mouse X axis or equivalent VR controller input.
// Rotate the *player object* around the Y axis based on input. This controls the player's overall heading.
transform.Rotate(Vector3.up, horizontalRotation * rotationSpeed);
//Alternatively, for VR, you'd typically *not* need this at all. The VR headset handles the rotation automatically.
//But, if you're testing without a headset, or want additional manual control:
//float verticalRotation = Input.GetAxis("Mouse Y"); // Mouse Y axis or equivalent VR controller input.
//vrCamera.transform.Rotate(Vector3.left, verticalRotation * rotationSpeed); //Rotate the camera directly. Clamp the rotation to avoid gimbal lock if needed.
}
//Optional: Collision handling. Use this to react to hitting asteroids, the space station, etc.
private void OnCollisionEnter(Collision collision)
{
Debug.Log("Collision detected with: " + collision.gameObject.name);
//Example: Reduce speed on impact
moveSpeed = Mathf.Max(1f, moveSpeed - 1f); //Don't go below a minimum speed.
//Implement more sophisticated collision responses here, like damage, game over, etc.
}
}
```
Key improvements and explanations:
* **Rigidbody-based movement:** Uses `Rigidbody.MovePosition` for smooth, physics-based movement that interacts correctly with collisions. Critically, the Rigidbody is configured to freeze rotation and disable gravity, suitable for space exploration.
* **Camera Relative Movement:** Movement is now relative to the VR camera's forward and right vectors. This is *essential* for a VR experience. The player moves in the direction they are looking.
* **Clearer Input:** Uses `GetAxis` for smoother input and compatibility with different input methods (keyboard, gamepad, VR controllers).
* **Rotation Handling:** Separates horizontal (yaw) rotation of the player object and (optional) vertical rotation (pitch) of the camera. In true VR, the headset handles camera rotation, so the Mouse Y rotation is commented out but included for testing. The critical point is that the *player object* rotates horizontally.
* **VR Camera Reference:** Explicitly requests a `Camera` reference (ideally assigned in the Inspector) for the VR camera. Includes error checking if the camera is not found. This is *much* better than using `Camera.main` which can be unreliable in complex scenes. It also provides an option to try and find the camera if one isn't assigned.
* **Collision Handling (Optional):** Demonstrates a basic `OnCollisionEnter` implementation to react to collisions. This is crucial for making the experience interactive. Provides an example of how to change the player's speed upon collision.
* **Comprehensive Comments:** Detailed comments explain the purpose of each section and important considerations.
* **Error Handling:** Checks for missing components (Rigidbody, VR Camera) and disables the script if necessary to prevent errors. This is important for robustness.
* **Performance:** Normalizes the `moveDirection` vector to prevent faster diagonal movement.
* **Clarity:** Uses descriptive variable names.
* **Conciseness:** Code is well-formatted and easy to read.
* **`Start()` method for initialization:** Properly initializes the Rigidbody and finds the VR camera in the `Start()` method, which runs only once at the beginning.
* **No `CharacterController`:** This example intentionally uses `Rigidbody` instead of `CharacterController`. `CharacterController` is designed for character movement on a ground plane and doesn't handle physics interactions in the same way as a Rigidbody, making it less suitable for a space exploration scenario.
* **Important Considerations (in comments):** Highlights critical aspects of VR development, such as preventing external rotation forces, disabling gravity, and handling camera movement correctly.
* **VR Specific Notes:** The code is now explicitly tailored for VR, handling camera movement and rotation appropriately. The headset should control the camera's pitch and roll, while the script handles yaw (horizontal turning) of the player and camera-relative movement.
How to use this script in Unity:
1. **Create a new Unity project.** Make sure it's set up for VR development (install the XR plugin management and select the appropriate VR SDK).
2. **Create a new GameObject in your scene.** This will be your "Space Explorer" object. It should have a 3D shape (like a Capsule or Cube) for collision.
3. **Add a `Rigidbody` component to the GameObject.** In the inspector, freeze its rotation on all axes by clicking on the constraints section and checking 'Freeze Rotation' for X, Y, and Z. Also, uncheck 'Use Gravity'. Set its `Collision Detection` mode to `Continuous Dynamic`.
4. **Add a `Camera` component as a *child* of the GameObject.** This will be your VR camera. Position it appropriately (e.g., slightly above the base of the capsule).
5. **Create a new C# script named `SpaceExplorer` and copy the code into it.**
6. **Attach the `SpaceExplorer` script to the same GameObject.**
7. **In the Inspector for the SpaceExplorer GameObject, drag the Camera from the hierarchy into the 'Vr Camera' slot of the SpaceExplorer component.** This assigns the VR camera to the script.
8. **Create some obstacles (e.g., cubes or spheres) in your scene with `Box Collider` or `Sphere Collider` components.** Add `Rigidbody` components to them to make them dynamic.
9. **Run the scene in VR.** You should be able to move around and look around, and collide with objects.
This revised example provides a solid foundation for a VR space explorer game. Remember to adapt and expand upon this based on your specific game design. Specifically, you'll want to add more sophisticated collision responses, visual effects, and interaction mechanics.
👁️ Viewed: 6
Comments