Advertisement
Guest User

Untitled

a guest
Jan 31st, 2018
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.64 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5.  
  6. public class PlayerController : MonoBehaviour {
  7.    
  8.     [SerializeField]
  9.     private float _force = 1.5f;
  10.     private Rigidbody2D _rb;
  11.     private bool _isMouseOver, _lmbClickedOnPlayer;
  12.     private Vector3 _mouseClickPosition;
  13.  
  14.     // Use this for initialization
  15.     void Start () {
  16.         _rb = GetComponent<Rigidbody2D> ();
  17.         _lmbClickedOnPlayer = false;
  18.         _isMouseOver = false;
  19.     }
  20.    
  21.     // Update is called once per frame
  22.     void Update () {
  23.        
  24.     }
  25.  
  26.     void OnMouseOver()
  27.     {
  28.         _isMouseOver = true;
  29.     }
  30.  
  31.     void OnMouseExit()
  32.     {
  33.         _isMouseOver = false;
  34.     }
  35.  
  36.     void OnMouseDown(){
  37.         if (_isMouseOver)
  38.             _lmbClickedOnPlayer = true;
  39.             _mouseClickPosition = Input.mousePosition;
  40.     }
  41.  
  42.     void OnMouseUp(){
  43.         if (_lmbClickedOnPlayer)
  44.         {
  45.             Dash();
  46.         }
  47.     }
  48.  
  49.     private void Dash()
  50.     {
  51.         Debug.Log("Dash");
  52.         _rb.bodyType = RigidbodyType2D.Dynamic;
  53.         Vector3 mouseUpPosition = Input.mousePosition;
  54.         Vector2 forceVector = CalculateCounterVector2D(_mouseClickPosition, mouseUpPosition) / 50;
  55.         _rb.AddForce(forceVector, ForceMode2D.Impulse);
  56.     }
  57.  
  58.     public void Cling(Vector2 position)
  59.     {
  60.         StartCoroutine(AdjustPosition(position));
  61.     }
  62.  
  63.     private IEnumerator AdjustPosition(Vector2 position)
  64.     {
  65.         while (Vector2.Distance(_rb.position, position) > 0.01)
  66.         {
  67.             _rb.MovePosition(position);
  68.             yield return new WaitForFixedUpdate();
  69.         }
  70.         _rb.bodyType = RigidbodyType2D.Static;
  71.         yield return null;
  72.     }
  73.  
  74.     Vector3 CalculateCounterVector2D(Vector3 origin, Vector3 end){
  75.         Vector3 result = (origin - end)*_force;
  76.         return new Vector2 (result.x, 2.5f * result.y);                    
  77.     }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement