Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Click to Move Mecanim C# script

Discussion in 'Scripting' started by Deleted User, Sep 15, 2013.

  1. Deleted User

    Deleted User

    Guest

    I was searching about for a Click to Move example in C# that ran with Mecanim and actually worked, I couldn't find one after much searching. So here is a basic one I made, debugged and live in a game.. It's basic for now.

    > Point and click raycasting
    > Terrain Gravity (Actually works and fixes issues with RigidBody)
    > Animation trigger on shared float with Mecanim
    > Transitions (Mecanim) from matching Raycasting position (Speed) and returns to 0 at point of destination.

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. [RequireComponent (typeof (Animator))]
    5.  
    6. public class CharControlAnim : MonoBehaviour {
    7.  
    8.     private Transform myTransform;              // this transform
    9.     private Vector3 destinationPosition;        // The destination Point
    10.     private float destinationDistance;          // The distance between myTransform and destinationPosition
    11.     public float Speed;                         // Speed at which the character moves
    12.     public float Direction;                    // The Speed the character will move
    13.     public float moveAnimSpeed;                // Float trigger for Float created in Mecanim (Use this to trigger transitions.
    14.     public float animSpeed = 1.5f;            // Animation Speed
    15.     public Animator anim;                     // Animator to Anim converter
    16.     public int idleState = Animator.StringToHash("Base Layer.Idle"); // String to Hash conversion for Mecanim "Base Layer"
    17.     public int runState = Animator.StringToHash("Base Layer.Run");  // String to Hash for Mecanim "Base Layer Run"
    18.     private AnimatorStateInfo currentBaseState;         // a reference to the current state of the animator, used for base layer
    19.     private Collider col;
    20.    
    21.        
    22.  
    23.  
    24.     void Start () {
    25.        
    26.         Physics.gravity = new Vector3(0,-200f,0); // used In conjunction with RigidBody for better Gravity (Freeze Rotation X,Y,Z), set mass and use Gravity)
    27.         anim = GetComponent<Animator>();
    28.         idleState = Animator.StringToHash("Idle"); // Duplicate added due to Bug
    29.         runState = Animator.StringToHash("Run");
    30.         myTransform = transform;                            // sets myTransform to this GameObject.transform
    31.         destinationPosition = myTransform.position;
    32.                           // prevents myTransform reset
    33.     }
    34.  
    35.     void FixedUpdate () {
    36.  
    37.         // keep track of the distance between this gameObject and destinationPosition      
    38.        
    39.         currentBaseState = anim.GetCurrentAnimatorStateInfo(0);
    40.        
    41.         destinationDistance = Vector3.Distance(destinationPosition, myTransform.position);
    42.                
    43.                  // Set's speed in reference to distance
    44.    
    45.             if(destinationDistance < .5f){     
    46.             Speed = 0;
    47.         }
    48.         else if(destinationDistance > .5f){        
    49.             Speed = 8;
    50.        
    51.             //Below sends Floats to Mecanim, Raycast set's speed to X until destination is reached animation is played until speed drops
    52.         }
    53.          
    54.         if (Speed > .5f){
    55.         anim.SetFloat ("moveAnimSpeed", 2.0f);}
    56.            
    57.                 else if (Speed < .5f){
    58.         anim.SetFloat ("moveAnimSpeed", 0.0f);} //
    59.  
    60.  
    61.         // Moves the Player if the Left Mouse Button was clicked
    62.        
    63.        
    64.         if (Input.GetMouseButtonDown(0) GUIUtility.hotControl ==0) {
    65.  
    66.             Plane playerPlane = new Plane(Vector3.up, myTransform.position);
    67.             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    68.             float hitdist = 0.0f;
    69.  
    70.             if (playerPlane.Raycast(ray, out hitdist)) {
    71.                 Vector3 targetPoint = ray.GetPoint(hitdist);
    72.                 destinationPosition = ray.GetPoint(hitdist);
    73.                 Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
    74.                 myTransform.rotation = targetRotation;
    75.                
    76.                
    77.             }
    78.    
    79.                 }  
    80.        
    81.    
    82.        
    83.  
    84.         // Moves the player if the mouse button is hold down
    85.         else if (Input.GetMouseButton(0) GUIUtility.hotControl ==0) {
    86.  
    87.             Plane playerPlane = new Plane(Vector3.up, myTransform.position);
    88.             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    89.             float hitdist = 0.0f;
    90.  
    91.             if (playerPlane.Raycast(ray, out hitdist)) {
    92.                 Vector3 targetPoint = ray.GetPoint(hitdist);
    93.                 destinationPosition = ray.GetPoint(hitdist);
    94.                 Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
    95.                 myTransform.rotation = targetRotation;
    96.             }
    97.         //  myTransform.position = Vector3.MoveTowards(myTransform.position, destinationPosition, moveSpeed * Time.deltaTime);
    98.         }
    99.  
    100.         // To prevent code from running if not needed
    101.         if(destinationDistance > .5f){
    102.             myTransform.position = Vector3.MoveTowards(myTransform.position, destinationPosition, Speed * Time.deltaTime);
    103.         }
    104.     }
    105. }
     
    Last edited by a moderator: Jan 25, 2014
    Braza likes this.
  2. Lition

    Lition

    Joined:
    Nov 2, 2013
    Posts:
    5
    Just what I needed Thank you
     
  3. snakeoilslim

    snakeoilslim

    Joined:
    Nov 14, 2013
    Posts:
    1
    This helped me out a great deal, thanks so much for posting it!
     
  4. Der_Kevin

    Der_Kevin

    Joined:
    Jan 2, 2013
    Posts:
    517
    Could someone show me how the Animator Have too like for this? screenshot is enough :)
     
  5. Deleted User

    Deleted User

    Guest

    Just attach the animator to the object (If it's not already there), as there is a required type at the top of the script.

    I'll also mentioned this script was based on a rigidbody setup, if you're using it in an RPG context don't forget to to freeze the correct axis to get it working correctly. Or you may find it doing a homer simpson floor spin and other weird issues may arise..

    I used this script for a hack and slash concept demo I did a while back ago, feel free to ask questions but as I don't use point and click any more so I can't send you screenshots.
     
  6. nvrmor

    nvrmor

    Joined:
    Apr 9, 2010
    Posts:
    5
    I got a ton of "unexpected symbol" and a parsing error in the console. I'm not at all familiar with scripting in JS much less C#. Will this work with script-driven root motion on a mecanim setup?
     
  7. Fidsh

    Fidsh

    Joined:
    Mar 9, 2015
    Posts:
    2
    Hey thanks for that script! Helped me a lot!
    But doesnt work perfect on uneven terrain :/ any idea how to run this with NavMesh? if i use "x.SetDestination (hitdist);" it doesnt work with the "speed" variable, have no idea how to do this :/
     
  8. D12Duke1

    D12Duke1

    Joined:
    Feb 14, 2016
    Posts:
    103
    Jesus Christ, all available information is for Unity 4.x . Is there nothing for 5.x??? Even the official crap doesn't work a lot of times.
     
  9. RavenOfCode

    RavenOfCode

    Joined:
    Apr 5, 2015
    Posts:
    869
    There are lots of tutorials in Unity 5, also if you need help with stuff just ask here on the forums. Another option is to find the simple differences between 4 and 5 http://docs.unity3d.com/Manual/UpgradeGuide5.html.