1
Answer

using UnityEngine; public class PlayerController : MonoBehaviour {

Photo of Aarav Yadav

Aarav Yadav

1d
57
1

using UnityEngine;

 

public class PlayerController : MonoBehaviour

{

    public float speed = 5f;

    public float jumpForce = 5f;

    private Rigidbody rb;

    private bool isGrounded;

 

    void Start()

    {

        rb = GetComponent<Rigidbody>();

    }

 

    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

        }

    }

}

Answers (1)