Search Unity

  1. If you have experience with import & exporting custom (.unitypackage) packages, please help complete a survey (open until May 15, 2024).
    Dismiss Notice
  2. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice

drag an object

Discussion in 'Scripting' started by gateway, Feb 24, 2009.

  1. gateway

    gateway

    Joined:
    Feb 11, 2009
    Posts:
    19
    I am trying to create a cube which can be dragged and rotated around a central pivot. Are there any scripts available that can be modified to do this?
     
  2. VJ_Anomolee

    VJ_Anomolee

    Joined:
    Dec 23, 2008
    Posts:
    40
    ya try mouse orbit script
     
  3. Mem Dixy

    Mem Dixy

    Joined:
    Feb 26, 2008
    Posts:
    51
    Interesting, I just barley answered another post about this same subject (http://forum.unity3d.com/viewtopic.php?t=19515).

    Here is a modified version of the script I used in that post so the object you are holding spins when you hold the Option button down.
    Code (csharp):
    1. #pragma strict
    2. // Attach this script to an orthographic camera.
    3. var spinSpeed = 60;
    4.  
    5. private var chicken : Transform;      // The chicken we will move.
    6. private var offSet : Vector3;      // The chicken's position relative to the mouse position.
    7.  
    8. function Update () {
    9.     var ray = camera.ScreenPointToRay(Input.mousePosition);      // Gets the mouse position in the form of a ray.
    10.     if (Input.GetMouseButtonDown(0)) {      // If we click the mouse...
    11.         var hit : RaycastHit;
    12.         if (Physics.Raycast(ray, hit, Mathf.Infinity)) {      // Then see if an chicken is beneath us using raycasting.
    13.             chicken = hit.transform;      // If we hit an chicken then hold on to the chicken.
    14.             offSet = chicken.position-ray.origin;      // This is so when you click on an chicken its center does not align with mouse position.
    15.             if (chicken.rigidbody) {
    16.                 chicken.rigidbody.isKinematic = true;
    17.             }
    18.         }
    19.     }
    20.     else if (Input.GetMouseButtonUp(0)) {
    21.         if (chicken.rigidbody) {
    22.             chicken.rigidbody.isKinematic = false;
    23.         }
    24.         chicken = null;      // Let go of the chicken.
    25.     }
    26.     if (chicken) {
    27.         chicken.position = Vector3(ray.origin.x+offSet.x, chicken.position.y, ray.origin.z+offSet.z);      // Only move the chicken on a 2D plane.
    28.         if (Input.GetButton("Fire2")) {
    29.             chicken.Rotate(0, spinSpeed*Time.deltaTime, 0);
    30.         }
    31.     }
    32. }
     
    ocimum likes this.
  4. auzette

    auzette

    Joined:
    Mar 23, 2009
    Posts:
    74
    Awesome example. Thank you! (albeit a couple months late).