Untitled
unknown
plain_text
2 years ago
1.4 kB
6
Indexable
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovement : MonoBehaviour { public float speed = 5f; public float jumpForce = 5f; public float groundDistance = 0.2f; public LayerMask groundLayer; private Rigidbody rb; private bool isGrounded; void Start() { rb = GetComponent<Rigidbody>(); } void Update() { // Move the player horizontally float horizontal = Input.GetAxis("Horizontal"); Vector3 movement = new Vector3(horizontal, 0f, 0f) * speed * Time.deltaTime; transform.Translate(movement, Space.Self); // Jump if the player is grounded and the jump button is pressed if (isGrounded && Input.GetButtonDown("Jump")) { rb.AddForce(new Vector3(0f, jumpForce, 0f), ForceMode.Impulse); isGrounded = false; } // Check if the player is grounded isGrounded = Physics.CheckSphere(transform.position, groundDistance, groundLayer, QueryTriggerInteraction.Ignore); } // Detect when the player collides with an obstacle void OnCollisionEnter(Collision collision) { if (collision.gameObject.CompareTag("Obstacle")) { Debug.Log("You hit an obstacle!"); // You could add a game over screen or restart the level here } } }
Editor is loading...