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

Joystick execution for walk animation instead of WSAD

Discussion in 'Animation' started by Getsy, Jan 25, 2015.

  1. Getsy

    Getsy

    Joined:
    Nov 4, 2013
    Posts:
    12
    Hi,

    The following code works nicely to do walk animation of human character using WSAD keyboard keys. I want to do this same animation working for Joystick control placed. So, I added right and left joystick controls and added variables in the code. Changing it for iPad app.
    Could someone kindly advise me, how can i make this human walk animation under Joystick movement instead of WSAD desktop system keys?

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. //Joystick moveJoystick;
    5.  
    6. // Require these components when using this script
    7. [RequireComponent(typeof (Animator))]
    8. [RequireComponent(typeof (CapsuleCollider))]
    9. [RequireComponent(typeof (Rigidbody))]
    10. public class PlayerControlScript : MonoBehaviour
    11. {
    12.     [System.NonSerialized]                  
    13.     public float meshMoveSpeed = 1.0f;
    14.     public float turningSpeed = 30;
    15.     public float movementSpeed = 5;
    16.  
    17.     [System.NonSerialized]
    18.     public float animSpeed = 1.5f;                // a public setting for overall animator animation speed
    19.  
    20.     private Animator anim;                            // a reference to the animator on the character
    21.     private AnimatorStateInfo currentBaseState;            // a reference to the current state of the animator, used for base layer
    22.     private AnimatorStateInfo layer2CurrentState;    // a reference to the current state of the animator, used for layer 2
    23.  
    24.     public Joystick rightJoystick = null;
    25.     public Joystick leftJoystick = null;
    26.     public float rotationSpeed = 0.5f;
    27.     public float speed = 3.0f;
    28.  
    29.     static int reloadState = Animator.StringToHash("Layer2.Reload");                // and are used to check state for various actions to occur
    30.  
    31.     static int switchWeaponState = Animator.StringToHash("Layer2.WeaponSwap");
    32.  
    33.  
    34.     void Update()                             //SAT_mouse script - Start
    35.     {
    36.         /*
    37.         float horizontal = Input.GetAxis("Horizontal") * turningSpeed * Time.deltaTime;
    38.         transform.Rotate(0, horizontal, 0);
    39.      
    40.         float vertical = Input.GetAxis("Vertical") * meshMoveSpeed * Time.deltaTime;
    41.         transform.Translate(0, 0, vertical);
    42.         */
    43.  
    44.         float horizontal = Input.GetAxis("Horizontal") * turningSpeed * Time.deltaTime;
    45.         transform.Rotate(0, horizontal, 0);
    46.      
    47.         float vertical = Input.GetAxis("Vertical") * meshMoveSpeed * Time.deltaTime;
    48.         transform.Translate(0, 0, vertical);
    49.  
    50.  
    51.         // END
    52.  
    53.     }                                        //SAT_mouse script - End
    54.     float joyStickInput (Joystick jstick)
    55.     {
    56.         Vector2 absJoyPos =new Vector2 (Mathf.Abs(jstick.position.x),
    57.                                         Mathf.Abs(jstick.position.y));
    58.         int xDirection = (jstick.position.x > 0) ? 1 : -1;
    59.         int yDirection = (jstick.position.y > 0) ? 1 : -1;
    60.         return ( ( absJoyPos.x > absJoyPos.y) ? absJoyPos.x * xDirection : absJoyPos.y * yDirection);
    61.     }
    62.     void Start ()
    63.     {
    64.         // initialising reference variables
    65.         anim = GetComponent<Animator>();                                        
    66.         if(anim.layerCount ==2)
    67.             anim.SetLayerWeight(1, 1);
    68.  
    69.         if(leftJoystick ==null){
    70.             GameObject objjoyStickLeft = GameObject.FindGameObjectWithTag("LeftJoystick") as GameObject;
    71.             //rotateJoystick = objjoyStickLeft.GetComponent();
    72.             leftJoystick = objjoyStickLeft.GetComponent<Joystick>();
    73.         }
    74.      
    75.         if(rightJoystick==null){
    76.             GameObject objjoyStickRight = GameObject.FindGameObjectWithTag("RightJoystick") as GameObject;
    77.             //moveJoystick = objjoyStickRight.GetComponent();
    78.             rightJoystick = objjoyStickRight.GetComponent<Joystick>();
    79.         }
    80.  
    81.     }
    82.  
    83.     void OnAnimatorMove() //Tells Unity that root motion is handled by the script
    84.     {
    85.         if(anim)
    86.         {
    87. //            Vector3 newPosition = transform.position;
    88. //            newPosition.z += anim.GetFloat("Speed")* meshMoveSpeed * Time.deltaTime;
    89. //            newPosition.x += anim.GetFloat("Direction") * meshMoveSpeed * Time.deltaTime;
    90. //            transform.position = newPosition;
    91.         }
    92.     }
    93.  
    94.  
    95.     void FixedUpdate ()
    96.     {
    97.         float h = Input.GetAxis("Horizontal");                // setup h variable as our horizontal input axis
    98.         float v = Input.GetAxis("Vertical");                // setup v variables as our vertical input axis
    99.         anim.SetFloat("Speed", v);                            // set our animator's float parameter 'Speed' equal to the vertical input axis              
    100.         anim.SetFloat("Direction", h);                         // set our animator's float parameter 'Direction' equal to the horizontal input axis      
    101.         anim.speed = animSpeed;                                // set the speed of our animator to the public variable 'animSpeed'
    102.         //anim.SetLookAtWeight(lookWeight);                    // set the Look At Weight - amount to use look at IK vs using the head's animation
    103.         currentBaseState = anim.GetCurrentAnimatorStateInfo(0);    // set our currentState variable to the current state of the Base Layer (0) of animation
    104.      
    105.         //Controls the movement speed
    106.         if(v <= 0.0f)
    107.         {
    108.             meshMoveSpeed = 2;  
    109.         }
    110.         else
    111.         {
    112.             meshMoveSpeed = 2;
    113.         }
    114.      
    115.  
    116.  
    117.     }
    118. }
    119.  
     
  2. Getsy

    Getsy

    Joined:
    Nov 4, 2013
    Posts:
    12
    I solved this myself.
     
  3. hidayat88

    hidayat88

    Joined:
    Jul 9, 2015
    Posts:
    2
    How did you solved it?
     
  4. Durins-Bane

    Durins-Bane

    Joined:
    Sep 21, 2012
    Posts:
    175
    Would also like to know if anyone can help
     
  5. SwaggyMcChicken

    SwaggyMcChicken

    Joined:
    Apr 13, 2015
    Posts:
    108
    You could easily just check the values for your movement vector or whatever you're using, and if it equals a certain value (like the Z cord not being equal to zero) you set a variable to play an anim
     
    swastika_pallai likes this.
  6. Durins-Bane

    Durins-Bane

    Joined:
    Sep 21, 2012
    Posts:
    175
    I tried adding this to the player relative controls.js


    Code (JavaScript):
    1.  
    2. player.GetComponent.<Animation>()["soldierWalk"].wrapMode=WrapMode.Loop;
    3. player.GetComponent.<Animation>()["soldierIdle"].wrapMode=WrapMode.Loop;
    4. var jPosy = Mathf.Abs(moveJoystick.position.y);
    5. if (jPosy < 0.1){
    6.   player.GetComponent.<Animation>().Play("soldierIdle");
    7. }
    8. else if (jPosy > 0.11){
    9.    player.GetComponent.<Animation>().Play("soldierWalk");
    10. }
    11.  

    This is the script that controls the players movement through the joysticks its just the one that comes with the standard assets.

    Code (JavaScript):
    1. //////////////////////////////////////////////////////////////
    2. // PlayerRelativeControl.js
    3. // Penelope iPhone Tutorial
    4. //
    5. // PlayerRelativeControl creates a control scheme similar to what
    6. // might be found in a 3rd person, over-the-shoulder game found on
    7. // consoles. The left stick is used to move the character, and the
    8. // right stick is used to rotate the character. A quick double-tap
    9. // on the right joystick will make the character jump.
    10. //////////////////////////////////////////////////////////////
    11.  
    12. #pragma strict
    13.  
    14. @script RequireComponent( CharacterController )
    15.  
    16. // This script must be attached to a GameObject that has a CharacterController
    17. var moveJoystick : Joystick;
    18. var rotateJoystick : Joystick;
    19.  
    20. var cameraPivot : Transform;                        // The transform used for camera rotation
    21.  
    22. var forwardSpeed : float = 4;
    23. var backwardSpeed : float = 1;
    24. var sidestepSpeed : float = 1;
    25. var jumpSpeed : float = 8;
    26. var inAirMultiplier : float = 0.25;                    // Limiter for ground speed while jumping
    27. var rotationSpeed : Vector2 = Vector2( 50, 25 );    // Camera rotation speed for each axis
    28.  
    29. var player : GameObject;
    30.  
    31.  
    32. private var thisTransform : Transform;
    33. private var character : CharacterController;
    34. private var cameraVelocity : Vector3;
    35. private var velocity : Vector3;                        // Used for continuing momentum while in air
    36.  
    37. function Start()
    38. {player = GameObject.FindWithTag("soldier");
    39.     // Cache component lookup at startup instead of doing this every frame    
    40.     thisTransform = GetComponent( Transform );
    41.     character = GetComponent( CharacterController );
    42.  
    43.     // Move the character to the correct start position in the level, if one exists
    44.     var spawn = GameObject.Find( "PlayerSpawn" );
    45.     if ( spawn )
    46.         thisTransform.position = spawn.transform.position;
    47. }
    48.  
    49. function OnEndGame()
    50. {
    51.     // Disable joystick when the game ends
    52.     moveJoystick.Disable();
    53.     rotateJoystick.Disable();
    54.  
    55.     // Don't allow any more control changes when the game ends
    56.     this.enabled = false;
    57. }
    58.  
    59. function Update()
    60. {
    61. var playerGun2 = GameObject.FindWithTag("gun").GetComponent(gun2);
    62.     if(playerGun2.firing){}
    63.  
    64. player.GetComponent.<Animation>()["soldierWalk"].wrapMode=WrapMode.Loop;
    65. player.GetComponent.<Animation>()["soldierIdle"].wrapMode=WrapMode.Loop;
    66. //var jPosy = Mathf.Abs(moveJoystick.position.y);
    67. if (moveJoystick.position.y < 0.1){
    68.   player.GetComponent.<Animation>().Play("soldierIdle");
    69. }
    70. else if (moveJoystick.position.y > 0.11){
    71.    player.GetComponent.<Animation>().Play("soldierWalk");
    72. }
    73.  
    74.  
    75.  
    76.     var movement = thisTransform.TransformDirection( Vector3( moveJoystick.position.x, 0, moveJoystick.position.y ) );
    77.  
    78.     // We only want horizontal movement
    79.     movement.y = 0;
    80.     movement.Normalize();
    81.  
    82.     var cameraTarget = Vector3.zero;
    83.  
    84.     // Apply movement from move joystick
    85.     var absJoyPos = Vector2( Mathf.Abs( moveJoystick.position.x ), Mathf.Abs( moveJoystick.position.y ) );
    86.     if ( absJoyPos.y > absJoyPos.x )
    87.     {
    88.         if ( moveJoystick.position.y > 0 ){
    89.             movement *= forwardSpeed * absJoyPos.y;
    90.          
    91.                         }
    92.         else
    93.         {
    94.             movement *= backwardSpeed * absJoyPos.y;
    95.             cameraTarget.z = moveJoystick.position.y * 0.75;
    96.          
    97.      
    98.         }
    99.  
    100.     }
    101.     else
    102.     {
    103.         movement *= sidestepSpeed * absJoyPos.x;
    104.      
    105.         // Let's move the camera a bit, so the character isn't stuck under our thumb
    106.         cameraTarget.x = -moveJoystick.position.x * 0.5;
    107.     }
    108.  
    109.     // Check for jump
    110.     if ( character.isGrounded )
    111.     {
    112.         if ( rotateJoystick.tapCount == 2)
    113.         {
    114.             // Apply the current movement to launch velocity    
    115.             //velocity = character.velocity;
    116.             //velocity.y = jumpSpeed;
    117.          
    118.                         var playerGun = GameObject.FindWithTag("gun").GetComponent(gun2);
    119.                         if(playerGun.firing){
    120.                         playerGun.firing = false;
    121.                      
    122.                         }else if(!playerGun.firing){
    123.                         playerGun.firing = true;
    124.                      
    125.                         }
    126.         }
    127.     }
    128.     else
    129.     {        
    130.         // Apply gravity to our velocity to diminish it over time
    131.         velocity.y += Physics.gravity.y * Time.deltaTime;
    132.      
    133.         // Move the camera back from the character when we jump
    134.         cameraTarget.z = -jumpSpeed * 0.25;
    135.      
    136.         // Adjust additional movement while in-air
    137.         movement.x *= inAirMultiplier;
    138.         movement.z *= inAirMultiplier;
    139.     }
    140.      
    141.     movement += velocity;
    142.     movement += Physics.gravity;
    143.     movement *= Time.deltaTime;
    144.  
    145.     // Actually move the character
    146.  
    147.     character.Move( movement );
    148.  
    149.     if ( character.isGrounded ){
    150.         // Remove any persistent velocity after landing
    151.         velocity = Vector3.zero;
    152.     }
    153.     // Seek camera towards target position
    154.     var pos = cameraPivot.localPosition;
    155.     pos.x = Mathf.SmoothDamp( pos.x, cameraTarget.x, cameraVelocity.x, 0.3 );
    156.     pos.z = Mathf.SmoothDamp( pos.z, cameraTarget.z, cameraVelocity.z, 0.5 );
    157.     cameraPivot.localPosition = pos;
    158.  
    159.     // Apply rotation from rotation joystick
    160.     if ( character.isGrounded )
    161.     {//player.animation.Play("soldierWalk");
    162.         var camRotation = rotateJoystick.position;
    163.         camRotation.x *= rotationSpeed.x;
    164.         camRotation.y *= rotationSpeed.y;
    165.         camRotation *= Time.deltaTime;
    166.      
    167.         // Rotate the character around world-y using x-axis of joystick
    168.         thisTransform.Rotate( 0, camRotation.x, 0, Space.World );
    169.      
    170.         // Rotate only the camera with y-axis input
    171.         cameraPivot.Rotate( -camRotation.y, 0, 0 );
    172.         var playerGun3 = GameObject.FindWithTag("gun").GetComponent(gun2);
    173.                  
    174.     playerGun3.Spawn.transform.Rotate( -camRotation.y, 0, 0 );
    175.     }
    176. }

    I just added the code above to the Update() function