Playing an Animation while moving a character forward using the W key?

how can i play my own Walk Animation while moving my character forward using the W key?

I asked in the Forum but did not understand the answer there.

http://forum.unity3d.com/viewtopic.php?t=37913

greetings Benajmin

Here's a guide on how you can use the Input Axis in Unity to control movement on how to play or stop an animation based on the current value of an axis.

  • You can use the Input manager (menu Edit > Project Settings > Input) to configure the control keys however you like. You can set the W key to be a button for the positive direction of the axis called Vertical. It is already configured that way by default.

  • Now, in scripting, you can read the value of the Vertical axis using the Input.GetAxis function to get the walk speed:

    var maxWalkSpeed = 10.0;
    var maxTurnSpeed = 100.0;
    function Update () {
        // Get the horizontal and vertical axis.
        // By default they are mapped to the arrow keys.
        // The value is in the range -1 to 1
        var walkSpeed = Input.GetAxis ("Vertical") * maxWalkSpeed;
        var turnSpeed = Input.GetAxis ("Horizontal") * maxTurnSpeed;
        // Move translation along the object's z-axis
        transform.Translate (0, 0, walkSpeed * Time.deltaTime);
        // Rotate around our y-axis
        transform.Rotate (0, turnSpeed * Time.deltaTime, 0);
    }
    
    
  • You can play the Walk animation whenever the walk speed is above a certain amount and stop it otherwise. The Animation.Play function plays a named animation. You can place this code in the Update function below the other code:

    if (walkSpeed > 5) {
        animation.Play("Walk");
    }
    else {
        animation.Stop("Walk");
    }
    
    

There is an script for player motion in Unity's Standard Assest's. Put that on you character and a character controller, which the script requires so it will do on its own, then adjust the size of the controller. Add this code at the beginning:

var rotateSpeed = 90; // This exposes it in the editor and you can change it.

Add this code after the controller.move:

transform.rotate(0,Input.GetAxis("Horizontal") * rotateSpeed,0);

For the animation, use CrossFade to get smooth blending;

if(Mathf.Abs(Input.GetAxisRaw("Vertical")) > .1) {
     animation.CrossFade("walk");
}

else {
     animation.CrossFade("idle")
}