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

Mecanim Attack Script

Discussion in 'Scripting' started by Paykoman, Nov 30, 2014.

  1. Paykoman

    Paykoman

    Joined:
    Jun 26, 2014
    Posts:
    500
    Hi guys im trying to implement Mecanim in my character, right now i hv only Base Layer when Idle is the Default State, then i hv transition from idle to run if Speed(float) greater then 0.1 and transition back when Speed less then 0.1. Here is everything right. Now i hv transition to idle to attack01 if attack(bool) is true and back idle if is false. I think until here everything is right in Animator part. But when i try play the idle/run transition are ok but the attack dont work. My script is this one. Can anyone help me plz? Probably is a script problem.

    Appreciate.

    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.     public int attack01State = Animator.StringToHash ("Base Layer.attack01");
    19.     private AnimatorStateInfo currentBaseState;         // a reference to the current state of the animator, used for base layer
    20.     private Collider col;
    21.    
    22.    
    23.    
    24.    
    25.     void Start () {
    26.        
    27.         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)
    28.         anim = GetComponent<Animator>();
    29.         idleState = Animator.StringToHash("Idle"); // Duplicate added due to Bug
    30.         runState = Animator.StringToHash("Run");
    31.         attack01State = Animator.StringToHash ("attack01");
    32.         myTransform = transform;                            // sets myTransform to this GameObject.transform
    33.         destinationPosition = myTransform.position;
    34.         // prevents myTransform reset
    35.     }
    36.    
    37.     void FixedUpdate () {
    38.        
    39.         // keep track of the distance between this gameObject and destinationPosition    
    40.        
    41.         currentBaseState = anim.GetCurrentAnimatorStateInfo(0);
    42.        
    43.         destinationDistance = Vector3.Distance(destinationPosition, myTransform.position);
    44.        
    45.         // Set's speed in reference to distance
    46.        
    47.         if(destinationDistance < .5f){    
    48.             Speed = 0;
    49.         }
    50.         else if(destinationDistance > .5f){      
    51.             Speed = 4;
    52.            
    53.             //Below sends Floats to Mecanim, Raycast set's speed to X until destination is reached animation is played until speed drops
    54.         }
    55.        
    56.         if (Speed > .5f){
    57.             anim.SetFloat ("moveAnimSpeed", 2.0f);}
    58.        
    59.         else if (Speed < .5f){
    60.             anim.SetFloat ("moveAnimSpeed", 0.0f);} //
    61.        
    62.        
    63.         // Moves the Player if the Left Mouse Button was clicked
    64.        
    65.        
    66.         if (Input.GetMouseButtonDown (0)) {
    67.            
    68.                         Plane playerPlane = new Plane (Vector3.up, myTransform.position);
    69.                         Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    70.                         float hitdist = 0.0f;
    71.            
    72.                         if (playerPlane.Raycast (ray, out hitdist)) {
    73.                                 Vector3 targetPoint = ray.GetPoint (hitdist);
    74.                                 destinationPosition = ray.GetPoint (hitdist);
    75.                                 Quaternion targetRotation = Quaternion.LookRotation (targetPoint - transform.position);
    76.                                 myTransform.rotation = targetRotation;
    77.                         }
    78.                 }
    79.        
    80.        
    81.        
    82.        
    83.         // Moves the player if the mouse button is hold down
    84.         else if (Input.GetMouseButton (0))
    85.         {
    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.             {
    93.                 Vector3 targetPoint = ray.GetPoint (hitdist);
    94.                 destinationPosition = ray.GetPoint (hitdist);
    95.                 Quaternion targetRotation = Quaternion.LookRotation (targetPoint - transform.position);
    96.                 myTransform.rotation = targetRotation;
    97.             }
    98.                         //  myTransform.position = Vector3.MoveTowards(myTransform.position, destinationPosition, moveSpeed * Time.deltaTime);
    99.         }
    100.         else if (currentBaseState.nameHash == idleState)
    101.         {
    102.             if(Input.GetKeyDown(KeyCode.Space))
    103.             {
    104.                 anim.SetBool("attack01", true);
    105.             }
    106.             else
    107.             {
    108.                 anim.SetBool("attack01", false);
    109.             }
    110.         }
    111.        
    112.         // To prevent code from running if not needed
    113.         if(destinationDistance > .5f){
    114.             myTransform.position = Vector3.MoveTowards(myTransform.position, destinationPosition, Speed * Time.deltaTime);
    115.         }
    116.     }
    117. }
    118.  
    119.  
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    you set the attack01 bool as a part of the "else if" chain for the mouse button check... so they can only attack if not moving?
     
  3. Paykoman

    Paykoman

    Joined:
    Jun 26, 2014
    Posts:
    500
    Y thats the point cant attack while run.. most be in idle state.. but i press the key to attack and dont work...i check the animator windows and nothing happen... the idle and run are working fine.
     
  4. Paykoman

    Paykoman

    Joined:
    Jun 26, 2014
    Posts:
    500
    Anyone? i already try change some things but still not working even trying with diferente keys to trigger tyhe attack action...
     
  5. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    ... If you dont want to only be able to attack whilst in the idle state... Dont put the attack logic in an "if idle state" condition....
    I.e. Remove lines 100, 101 and 110
     
  6. Paykoman

    Paykoman

    Joined:
    Jun 26, 2014
    Posts:
    500
    Hi ok i try remove that lines but not they attack anamation keep not working and i get this warnin

    Parameter 'attack01' does not exist. in line 107, if the image bellow helps too there it is.

    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_Ready"); // String to Hash conversion for Mecanim "Base Layer"
    17.     public int runState = Animator.StringToHash("Base Layer.Run_Impulse");  // String to Hash for Mecanim "Base Layer Run"
    18.     public int attack01State = Animator.StringToHash ("Base Layer.attack01");
    19.     private AnimatorStateInfo currentBaseState;         // a reference to the current state of the animator, used for base layer
    20.     private Collider col;
    21.    
    22.    
    23.    
    24.    
    25.     void Start () {
    26.        
    27.         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)
    28.         anim = GetComponent<Animator>();
    29.         idleState = Animator.StringToHash("Idle_Ready"); // Duplicate added due to Bug
    30.         runState = Animator.StringToHash("Run_Impulse");
    31.         attack01State = Animator.StringToHash ("attack01");
    32.         myTransform = transform;                            // sets myTransform to this GameObject.transform
    33.         destinationPosition = myTransform.position;
    34.         // prevents myTransform reset
    35.     }
    36.    
    37.     void FixedUpdate () {
    38.        
    39.         // keep track of the distance between this gameObject and destinationPosition    
    40.        
    41.         currentBaseState = anim.GetCurrentAnimatorStateInfo(0);
    42.        
    43.         destinationDistance = Vector3.Distance(destinationPosition, myTransform.position);
    44.        
    45.         // Set's speed in reference to distance
    46.        
    47.         if(destinationDistance < .5f){    
    48.             Speed = 0;
    49.         }
    50.         else if(destinationDistance > .5f){      
    51.             Speed = 4;
    52.            
    53.             //Below sends Floats to Mecanim, Raycast set's speed to X until destination is reached animation is played until speed drops
    54.         }
    55.        
    56.         if (Speed > .5f){
    57.             anim.SetFloat ("moveAnimSpeed", 2.0f);}
    58.        
    59.         else if (Speed < .5f){
    60.             anim.SetFloat ("moveAnimSpeed", 0.0f);} //
    61.        
    62.        
    63.         // Moves the Player if the Left Mouse Button was clicked
    64.        
    65.        
    66.         if (Input.GetMouseButtonDown (0)) {
    67.            
    68.                         Plane playerPlane = new Plane (Vector3.up, myTransform.position);
    69.                         Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    70.                         float hitdist = 0.0f;
    71.            
    72.                         if (playerPlane.Raycast (ray, out hitdist)) {
    73.                                 Vector3 targetPoint = ray.GetPoint (hitdist);
    74.                                 destinationPosition = ray.GetPoint (hitdist);
    75.                                 Quaternion targetRotation = Quaternion.LookRotation (targetPoint - transform.position);
    76.                                 myTransform.rotation = targetRotation;
    77.                         }
    78.                 }
    79.        
    80.        
    81.        
    82.        
    83.         // Moves the player if the mouse button is hold down
    84.         else if (Input.GetMouseButton (0))
    85.         {
    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.             {
    93.                 Vector3 targetPoint = ray.GetPoint (hitdist);
    94.                 destinationPosition = ray.GetPoint (hitdist);
    95.                 Quaternion targetRotation = Quaternion.LookRotation (targetPoint - transform.position);
    96.                 myTransform.rotation = targetRotation;
    97.             }
    98.                         //  myTransform.position = Vector3.MoveTowards(myTransform.position, destinationPosition, moveSpeed * Time.deltaTime);
    99.         }
    100.  
    101.         if(Input.GetKeyDown(KeyCode.Space))
    102.         {
    103.             anim.SetBool("attack01", true);
    104.         }
    105.         else
    106.         {
    107.             anim.SetBool("attack01", false);
    108.         }
    109.            
    110.         // To prevent code from running if not needed
    111.         if(destinationDistance > .5f){
    112.             myTransform.position = Vector3.MoveTowards(myTransform.position, destinationPosition, Speed * Time.deltaTime);
    113.         }
    114.     }
    115. }
    116.  
     
  7. TonyLi

    TonyLi

    Joined:
    Apr 10, 2012
    Posts:
    12,523
    Change this:
    Code (csharp):
    1. anim.SetBool("attack01", true);
    to:
    Code (csharp):
    1. anim.SetBool("Attack", true);
    (And do the same for SetBool(..., false).)
     
  8. Paykoman

    Paykoman

    Joined:
    Jun 26, 2014
    Posts:
    500
    No errors now but:
    - attack keep not working;
    - run animation stop at mid and never stop after start run;

    This mecanim are amazing but hard to configure.... :(
     
  9. Paykoman

    Paykoman

    Joined:
    Jun 26, 2014
    Posts:
    500
    The big problem here is that i want to move and attack like diablo type 3rd person top view, because if its wasd it will be muhc easy to do.. :s
     
  10. TonyLi

    TonyLi

    Joined:
    Apr 10, 2012
    Posts:
    12,523
    1. Change the transition attack01--->Idle_Ready to transition only on Exit Time, not on the value of Attack.

    2. Change this code:
    Code (csharp):
    1. if(Input.GetKeyDown(KeyCode.Space))
    2. {
    3.   anim.SetBool("attack01", true);
    4. }
    5. else
    6. {
    7.   anim.SetBool("attack01", false);
    8. }
    to:
    Code (csharp):
    1. if (Input.GetKeyDown(KeyCode.Space)) anim.SetTrigger("Attack");
    3. Make sure your animations are set to Loop.
     
  11. Paykoman

    Paykoman

    Joined:
    Jun 26, 2014
    Posts:
    500
    Nvm i will leave this.. now character is idle fine, then i click to move and it run and idle same time dont leaving the same place all the time and attack keep not working... if coding animations are not easy but still work even not perfect mecanim is killing me... :(