using UnityEngine;
public class Controller : MonoBehaviour
{
public float speed = 10f;
public float jumpForce = 10f;
public Rigidbody rb; // Reference to the Rigidbody component
public LayerMask groundLayer; // Specify the Ground layer
private bool isGrounded;
void Start()
{
rb = GetComponent(); // Assign the Rigidbody component
}
void Update()
{
// Check if the character is grounded
isGrounded = IsGrounded();
// Move the character forward
float vertical = 1f; // Set a constant forward movement
Vector3 move = transform.forward * vertical * speed;
// Apply movement
rb.MovePosition(rb.position + move * Time.deltaTime);
// Jump only when the Jump button is pressed and the character is grounded
if (Input.GetButtonDown("Jump") && isGrounded)
{
Jump(); // Call the Jump method
}
}
// Make the Jump method public so it can be accessed from the Unity Editor
public void Jump()
{
rb.velocity = new Vector3(rb.velocity.x, jumpForce, rb.velocity.z);
}
bool IsGrounded()
{
// Check if the character is close to the ground using the collider
float raycastDistance = 0.2f;
RaycastHit hit;
if (Physics.Raycast(transform.position, Vector3.down, out hit, raycastDistance, groundLayer))
{
return true;
}
return false;
}
}