Pro_Unit

Untitled

Feb 20th, 2020
232
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.68 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class Move : MonoBehaviour
  6. {
  7.     [SerializeField] private float _horisontalSpeed;
  8.     [SerializeField] private float _verticalImpulse;
  9.     private float _speedX;
  10.     private Rigidbody2D _rigidBody;
  11.     private bool _isGrounded;
  12.     private void Start()
  13.     {
  14.         _rigidBody = GetComponent<Rigidbody2D>();
  15.     }
  16.     public void LeftDown()
  17.     {
  18.         _speedX = -_horisontalSpeed;
  19.     }
  20.     public void RightDown()
  21.     {
  22.         _speedX = _horisontalSpeed;
  23.     }
  24.     public void Stop()
  25.     {
  26.         _speedX = 0;
  27.     }
  28.     public void OnClickJump()
  29.     {
  30.         if (_isGrounded)
  31.             _rigidBody.AddForce(new Vector2(0, _verticalImpulse), ForceMode2D.Impulse);
  32.     }
  33.     // Update is called once per frame
  34.     private void FixedUpdate()
  35.     {  
  36.         //? Сохраняем предыдущую позицию
  37.         Vector2 position = _rigidBody.position;
  38.         //? смещаем её на вектор в права с умножением на скорость.
  39.         //? P.S. если _speedX < 0 - двидение в лево, _speedX > 0 - движение вправо
  40.         position += Vector2.right * _speedX;
  41.         //? применяем двжение через Rigidbody
  42.         _rigidBody.MovePosition(position);
  43.     }
  44.  
  45.     private void OnCollisionEnter2D(Collision2D collision)
  46.     {
  47.         if (collision.gameObject.CompareTag("Ground"))
  48.             _isGrounded = true;
  49.  
  50.     }
  51.     private void OnCollisionExit2D(Collision2D collision)
  52.     {
  53.         if (collision.gameObject.CompareTag("Ground"))
  54.             _isGrounded = false;
  55.  
  56.     }
  57. }
Add Comment
Please, Sign In to add comment