using System; using UnityEngine.UI; using TMPro; using UnityEngine; using UnityEngine.InputSystem; public class BallController : MonoBehaviour { [SerializeField] private TMP_Text _pickupLeftText; [SerializeField] private TMP_Text _timeSpentText; [SerializeField] private TMP_Text _winText; [SerializeField] Button _playAgain; [SerializeField] Button _quit; int _pickupLeft; float _ballSpeed; float _brakeForce; float _jumpForce; Rigidbody _ball; float _outOfBounds = -1.8f; private Vector2 _moveInput; private PlayerControls _controls; void Start() { _ballSpeed = 5f; _brakeForce = 0.3f; _jumpForce = 300f; _pickupLeft = GameObject.FindGameObjectsWithTag("PickUp").Length; transform.position = new Vector3(0, 0.5f, 0); } private void Awake() { _ball = GetComponent(); _controls = new PlayerControls(); } private void OnEnable() { _controls.Enable(); _controls.Player.Move.performed += ctx => _moveInput = ctx.ReadValue(); _controls.Player.Move.canceled += ctx => _moveInput = Vector2.zero; _controls.Player.Jump.performed += ctx => { if (transform.position.y < 1.0f) { _ball.AddForce(Vector3.up * _jumpForce); } }; } public void OnMove(InputAction.CallbackContext context) { _moveInput = context.ReadValue(); } private void FixedUpdate() { Vector3 direction = new Vector3(_moveInput.x, 0, _moveInput.y); _ball.AddForce(direction * _ballSpeed); if (direction == Vector3.zero) { _ball.AddForce(-_ball.linearVelocity * _brakeForce); } } void Update() { CheckPlayerOut(); UpdateGUI(); } void UpdateGUI() { _pickupLeftText.text = "Left: " + _pickupLeft.ToString(); _timeSpentText.text = "Tid: " + Time.timeSinceLevelLoad.ToString("F1") + "s"; } void OnTriggerEnter(Collider other) { other.gameObject.SetActive(false); _pickupLeft--; if (_pickupLeft == 0) LevelDone(); } void LevelDone() { _pickupLeftText.gameObject.SetActive(false); _timeSpentText.gameObject.SetActive(false); _winText.text = "Snyggt jobbat!\nDin tid: " + Time.timeSinceLevelLoad.ToString("F1") + "s"; _winText.gameObject.SetActive(true); _playAgain.gameObject.SetActive(true); _quit.gameObject.SetActive(true); } void CheckPlayerOut() { if (transform.position.y < _outOfBounds) { transform.position = new Vector3(0, 1f, 0); transform.rotation = Quaternion.Euler(0, 0, 0); } } }