-
-
Save HolyMonkey/910a23147ef6a41e3aaffa278c2123f3 to your computer and use it in GitHub Desktop.
JumpManager.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
//Внезапно хауди списывая код с уроков забыл послушать что он означал | |
//В конечном итоге у него получился просто постоянный скейлинг гравитации | |
[RequireComponent(typeof(Rigidbody))] | |
class GravityScale : MonoBehaviour | |
{ | |
[SerializeField] private float _scale = 10f; | |
private Rigidbody _self; | |
private void Awake() | |
{ | |
_self = transform.GetComponent<Rigidbody>(); | |
} | |
private void FixedUpdate() | |
{ | |
_self.velocity += Physics.gravity * (_scale - 1) * Time.deltaTime; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
class Ground : MonoBehaviour { } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
//Если делаешь GetComponent не забывай про RequireComponent | |
[RequireComponent(typeof(Rigidbody))] | |
public class Jump : MonoBehaviour | |
{ | |
[SerializeField] private float _force; //Jump - Force. А не Jump.JumpForce. | |
private Rigidbody _self; | |
private bool _jumping; | |
private void Awake() | |
{ | |
_self = transform.GetComponent<Rigidbody>(); | |
} | |
private void Update() | |
{ | |
//нет ничего страшного в придание импульса в Update, применится он всё равно в FixedUpdate | |
if (Input.GetKeyDown(KeyCode.Space)) //Использовать строквые литералы в коде плохая идея | |
TryJump(); | |
} | |
private void OnCollisionEnter(Collision collision) | |
{ | |
//В целом идея проверять нахождение на земле через коллизии способ плохой | |
//Но реализовать его можно гораздо лучше, например сделав проверку по наличию компонента а не тега | |
if (collision.gameObject.TryGetComponent(out Ground ground)) | |
_jumping = false; | |
} | |
private void TryJump() | |
{ | |
if (_jumping) | |
return; | |
_self.AddForce(Vector3.up * _force, ForceMode.Impulse); | |
_jumping = true; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
[RequireComponent(typeof(Rigidbody))] | |
class Movement : MonoBehaviour | |
{ | |
[SerializeField] private float _unitsPerSecond = 15f; | |
private Rigidbody _self; | |
private void Awake() | |
{ | |
_self = transform.GetComponent<Rigidbody>(); | |
} | |
private void FixedUpdate() | |
{ | |
Vector3 offset = transform.forward * _unitsPerSecond * Time.deltaTime; | |
_self.MovePosition(transform.position + offset); | |
} | |
} |
Роман, я думаю стоит остановиться на видео уроках по юнити, хауди многому научился, пора начать жесткое, давай английский по 300 bucks, ждем курс!
Форчанский появился, ща взглянем )
- TryGetComponent на твоем месте я бы по рукам бил за любое использование GetComponent вне Start/Awake.
И кстати, проверка по слоям работает быстрее этого варианта (примерно в 2 раза).- KeyCode.Space - хардкод, круто )
Чтобы поменять инпут - придется менять скрипт, браво!
А это, игроку чтоб поменять бинд - надо декомпилировать игру? :]
А вообще уже давно есть New Input System.- AddForce в Update, тоже надо по рукам бить за такое.
Он то может и выполнится нормально, но там очень много но.
Вообще это Bad Practice писать так код.- Булевы переменные лучше именовать с префиксами "is", "has", "can" (в данном случае оно "adds value" как раз, если что)
Это рекомендация Microsoft Naming Convention- _self. Конечно это не Python, а C#. Но здесь есть ключевое слово this. Мягко говоря, это не нарушение. Но имхо условный _rb смотрелся бы лучше и был более понятным.
- Файлик контроллера лучше называть с постфиксом Controller.
Например, JumpController, MovementController и т.д.
Почитай, дружок пирожок.
Какой еще n@xui "дружок пирожок", он же вроде не твоя ежедневная еда
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Имхо ебейший оверинжиринг.