Search Unity

Player Movement Using Velocity C#

Discussion in 'Scripting' started by jamesman, Jan 24, 2015.

  1. jamesman

    jamesman

    Joined:
    Oct 13, 2013
    Posts:
    51
    I have been working a while on this movement script and its been holding me back. I am new to c# but I have had experience on other languages. The only way I can move my character is with the x,y,z axis. But I ran into problems such a turning. If i have Input Vertical on the z axis and i rotate my character, he will still move on the z axis.
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Walk : MonoBehaviour {
    5.     public Vector3 input;
    6.     public float maxSpeed = 10f;
    7.     // Use this for initialization
    8.     void Start () {
    9.         animation ["Rig.001|Attack"].layer = 2;
    10.         animation ["Rig.001|Walk"].layer = 1;
    11.         animation ["Rig.001|Idle"].layer = 1;
    12.     }
    13.    
    14.     // Update is called once per frame
    15.     void Update () {
    16.  
    17.  
    18.  
    19.        
    20.  
    21.         //this is the only way i can think of how to move it.
    22.         input = new Vector3 (0, 0, Input.GetAxisRaw ("Vertical"));
    23.            
    24.            
    25.  
    26.             rigidbody.velocity = (input*maxSpeed);
    27.            
    28.            
    29.            
    30.            
    31.            
    32.             if (Mathf.Abs (Input.GetAxisRaw ("Vertical")) > 0.1)
    33.                
    34.                 animation.CrossFade ("Rig.001|Walk");
    35.             else
    36.                 animation.CrossFade ("Rig.001|Idle");
    37.            
    38.            
    39.             if (Input.GetButtonDown ("Fire1")) {
    40.  
    41.                
    42.                 animation.CrossFade ("Rig.001|Attack");
    43.  
    44.  
    45.                
    46.             }
    47.            
    48.            
    49.             print (rigidbody.velocity);
    50.  
    51.        
    52.            
    53.                
    54.    
    55.     }
    56. }
    57.  
     
  2. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
  3. jamesman

    jamesman

    Joined:
    Oct 13, 2013
    Posts:
    51
    I decided to switch to translation instead of a rigidbody for movement. It works great for what I am doing.