Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class Move : MonoBehaviour
- {
- [SerializeField] private float _horisontalSpeed;
- [SerializeField] private float _verticalImpulse;
- private float _speedX;
- private Rigidbody2D _rigidBody;
- private bool _isGrounded;
- private void Start()
- {
- _rigidBody = GetComponent<Rigidbody2D>();
- }
- public void LeftDown()
- {
- _speedX = -_horisontalSpeed;
- }
- public void RightDown()
- {
- _speedX = _horisontalSpeed;
- }
- public void Stop()
- {
- _speedX = 0;
- }
- public void OnClickJump()
- {
- if (_isGrounded)
- _rigidBody.AddForce(new Vector2(0, _verticalImpulse), ForceMode2D.Impulse);
- }
- // Update is called once per frame
- private void FixedUpdate()
- {
- //? Сохраняем предыдущую позицию
- Vector2 position = _rigidBody.position;
- //? смещаем её на вектор в права с умножением на скорость.
- //? P.S. если _speedX < 0 - двидение в лево, _speedX > 0 - движение вправо
- position += Vector2.right * _speedX;
- //? применяем двжение через Rigidbody
- _rigidBody.MovePosition(position);
- }
- private void OnCollisionEnter2D(Collision2D collision)
- {
- if (collision.gameObject.CompareTag("Ground"))
- _isGrounded = true;
- }
- private void OnCollisionExit2D(Collision2D collision)
- {
- if (collision.gameObject.CompareTag("Ground"))
- _isGrounded = false;
- }
- }
Add Comment
Please, Sign In to add comment