Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How can I make a rotating handle that the player can drag to rotate ?

Discussion in '2D' started by Cloviren, Mar 4, 2015.

  1. Cloviren

    Cloviren

    Joined:
    Mar 4, 2015
    Posts:
    3
    Hi guys , I currenctly suck with this . I'm having a wheel with a handle , I want the players to be able to touch and drag the handle in clockwise motion to rotate the entire wheels and when the players drag the handle counter clockwise , the wheel will stuck and won't rotate back .
    Here's some images if you don't understand .



    Thanks so much :)
     
  2. PGJ

    PGJ

    Joined:
    Jan 21, 2014
    Posts:
    899
    Try something like this:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Rotate : MonoBehaviour
    5. {
    6.     private const float startAngle = 45;
    7.     void Update ()
    8.     {
    9.         Vector2 mp = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    10.         Collider2D c = Physics2D.OverlapPoint(mp);
    11.  
    12.         if (c != null && c.gameObject.tag == "Handle" && Input.GetButton("Fire1"))
    13.         {
    14.             Vector2 dir = mp - (Vector2)transform.position;
    15.  
    16.             float angle = Mathf.Atan2(dir.y, dir.x)*Mathf.Rad2Deg - startAngle;
    17.  
    18.             if (angle < transform.eulerAngles.z)
    19.             {
    20.                 transform.eulerAngles = new Vector3(0, 0, angle);
    21.             }
    22.         }
    23.     }
    24. }
    25.  
     
    conuletv likes this.