Advertisement
Guest User

Untitled

a guest
Dec 22nd, 2019
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.42 KB | None | 0 0
  1. public class Player : MonoBehaviour
  2. {
  3.         [SerializeField] private float speed;
  4.  
  5.         private Camera camera;
  6.         private Vector2 touchPosition;
  7.         private Vector2 offset;
  8.         private Vector2 direction;
  9.         private Rigidbody2D rb2d;
  10.        
  11.         private void Awake()
  12.         {
  13.                 rb2d = GetComponent<Rigidbody2D>();
  14.                 camera = Camera.main;
  15.                
  16.                 Input.multiTouchEnabled = false;
  17.  
  18.                 direction = transform.position;
  19.         }
  20.  
  21.         private void Update()
  22.         {
  23.                 GetInput();
  24.         }
  25.  
  26.         private void FixedUpdate()
  27.         {
  28.                 rb2d.MovePosition(direction);
  29.         }
  30.  
  31.         private void GetInput()
  32.         {
  33.                 if (!Input.GetMouseButton(0)) return;
  34.                
  35.                 touchPosition = camera.ScreenToWorldPoint(Input.mousePosition);
  36.                
  37.                 if (Input.GetMouseButtonDown(0))
  38.                 {
  39.                         offset = (Vector2)transform.position - touchPosition;
  40.                 }
  41.                
  42.                 if (Input.GetMouseButton(0))
  43.                 {
  44.                         direction = touchPosition * speed + offset;
  45.                 }
  46.                
  47.                 if (Input.GetMouseButtonUp(0))
  48.                 {
  49.                         direction = transform.position;
  50.                 }
  51.         }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement