using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed = 5f;
public float jumpForce = 5f;
private Rigidbody rb;
private bool isGrounded;
void Start()
{
rb = GetComponent
}
void Update()
{
// Move forward constantly
transform.Translate(Vector3.forward * speed * Time.deltaTime);
// Jump if grounded and space is pressed
if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
isGrounded = false;
}
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Ground"))
isGrounded = true;
if (collision.gameObject.CompareTag("Obstacle"))
{
Debug.Log("Game Over!");
Time.timeScale = 0; // Freeze game
}
}
}
Eliana BlakePosted May 18, 2025, 4:23 AM
Thank you for sharing the detailed code snippet for the PlayerController class in Unity! This script provides the foundation for controlling a player character in a game environment. Let's break down some key components and functionalities:
1. Speed and Jump Force:
- The public float variables `speed` and `jumpForce` are used to control how fast the player character moves forward and how high the player can jump, respectively.
2. Rigidbody and Grounded State:
- The private `Rigidbody rb` variable is used to access the Rigidbody component of the game object this script is attached to.
- The private bool `isGrounded` is a flag that determines whether the player is currently on the ground or not. This is crucial for handling jumping mechanics.
3. Start() Method:
- In the `Start()` method, the `rb` variable is assigned the Rigidbody component of the object, allowing us to manipulate the object's physics.
4. Update() Method:
- The `Update()` method is called every frame and contains the main logic of the player controller.
- It moves the player object forward continuously based on the defined `speed`.
- It checks for the spacebar press to trigger a jump if the player is grounded. Upon jumping, the player's Rigidbody receives an upward force, and the grounded state is set to false to prevent continuous jumping.
5. OnCollisionEnter() Method:
- This method is called when the player collides with other objects in the scene.
- If the collision is with an object tagged as "Ground," the `isGrounded` flag is set to true, allowing the player to jump again.
- If the collision is with an object tagged as "Obstacle," a game over message is logged, and the game time scale is set to 0, effectively freezing the game.
By following this script structure and incorporating it into a Unity project with appropriate physics settings and game objects, you can create a basic player controller that moves forward, jumps, and responds to collisions with the ground and obstacles.
If you have any specific questions or need further clarification on any part of this script, feel free to ask!