Placido_GDD

BallControl

Apr 11th, 2022 (edited)
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.87 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class BallControl : MonoBehaviour
  6. {
  7.  
  8.     private GameObject cueBall;
  9.     public float power = 10.0f;
  10.     public float maxDrag = 5.0f;
  11.  
  12.     private LineRenderer lr;
  13.     private Rigidbody rb;
  14.  
  15.  
  16.     Vector3 dragStartPos;
  17.     Touch touch;
  18.  
  19.     private void Start()
  20.     {
  21.         cueBall = GameObject.Find("CueBall");
  22.         rb = cueBall.GetComponent<Rigidbody>();
  23.         lr = cueBall.GetComponent <LineRenderer>();
  24.     }
  25.  
  26.     private void Update()
  27.     {
  28.         TouchActions();
  29.     }
  30.      
  31.     void TouchActions()
  32.     {
  33.         if (Input.touchCount > 0)
  34.         {
  35.             touch = Input.GetTouch(0);
  36.             if (touch.phase == TouchPhase.Began)
  37.             {
  38.                 DragStart();
  39.             }
  40.             if (touch.phase == TouchPhase.Moved)
  41.             {
  42.                 Dragging();
  43.             }
  44.             if (touch.phase == TouchPhase.Ended)
  45.             {
  46.                 DragRelease();
  47.             }
  48.         }
  49.     }
  50.     void DragStart()
  51.     {
  52.         dragStartPos = Camera.main.ScreenToWorldPoint(touch.position);
  53.         dragStartPos.y = 0;
  54.         lr.positionCount = 1;
  55.         lr.SetPosition(0,dragStartPos);
  56.  
  57.     }
  58.     void Dragging()
  59.     {
  60.         Vector3 draggingPos = Camera.main.ScreenToWorldPoint(touch.position);
  61.         draggingPos.y = 0;
  62.         lr.positionCount = 2;
  63.         lr.SetPosition(1,draggingPos);        
  64.     }
  65.  
  66.     void DragRelease()
  67.     {
  68.         lr.positionCount = 0;
  69.         Vector3 dragReleasePos = Camera.main.ScreenToWorldPoint(touch.position);
  70.         dragReleasePos.y = 0;
  71.         Vector3 force = dragStartPos - dragReleasePos;
  72.         Vector3 clampedForce = Vector3.ClampMagnitude(force, maxDrag) * power;
  73.         Debug.Log(clampedForce);
  74.         rb.AddForce(clampedForce,ForceMode.Impulse);
  75.     }
  76. }
  77.  
Add Comment
Please, Sign In to add comment