Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
4 captures
13 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
0
Question by DavidRoad · May 26 at 10:54 AM · 3d

Footsteps Not Working When Running

I Have This FootstepScript It Works Fine But When I Run I Don't Hear The Footstep Sounds Anymore These Are Javascripts

My FootSteps Script:

 var ground : AudioClip[];
 private var step : boolean = true;
 var audioStepLengthWalk : float = 0.45;
 var audioStepLengthRun : float = 0.82;
 
 function OnControllerColliderHit (hit : ControllerColliderHit) {
 var controller : CharacterController = GetComponent(CharacterController);
 
 if (controller.isGrounded && controller.velocity.magnitude < 7 && controller.velocity.magnitude > 5 && hit.gameObject.tag == "Ground"  && step == true || 
 controller.isGrounded && controller.velocity.magnitude < 7 && controller.velocity.magnitude > 5 && hit.gameObject.tag == "Grass" && step == true ) {
         WalkOnGround();    
         RunOnGround();
     }
 }
 /////////////////////////////////// Ground ////////////////////////////////////////
 function WalkOnGround() {
     step = false;
     audio.clip = ground[Random.Range(0, ground.length)];
     audio.volume = .1;
     audio.Play();
     yield WaitForSeconds (audioStepLengthWalk);
     step = true;
 }
 
 function RunOnGround()
 {
     if(Input.GetKeyDown("left shift"))
     {
         step = false;
         audio.clip = ground[Random.Range(0, ground.length)];
         audio.volume = .1;
         audio.Play();
         yield WaitForSeconds (audioStepLengthRun);
         step = true;
     }
 }
 
 @script RequireComponent(AudioSource)
 @script AddComponentMenu("CharacterPlayer/FootstepGrass")


And Heres My PlayerScript

 var walkSpeed = 6.0;
  var runSpeed = 11.0;
  private var crouchSpeed = 3.0;
   
  // If true, diagonal speed (when strafing + moving forward or back) can't exceed normal move speed; otherwise it's about 1.4 times faster
  var limitDiagonalSpeed = true;
   
  // If checked, the run key toggles between running and walking. Otherwise player runs if the key is held down and walks otherwise
  // There must be a button set up in the Input Manager called "Run"
  var enableRun = true;
  var enableCrouch = true;
   
  var jumpSpeed = 8.0;
  var gravity = 20.0;
  
  var enableFallingDammage = true;  
  // Units that player can fall before a falling damage function is run. To disable, type "infinity" in the inspector
  var fallingDamageThreshold = 10.0;
  var fallingDammageMultiplier = 2;
   
  // If the player ends up on a slope which is at least the Slope Limit as set on the character controller, then he will slide down
  var slideWhenOverSlopeLimit = false;
   
  // If checked and the player is on an object tagged "Slide", he will slide down it regardless of the slope limit
  var slideOnTaggedObjects = false;
   
  var slideSpeed = 12.0;
   
  // If checked, then the player can change direction while in the air
  var airControl = false;
   
  // Small amounts of this results in bumping when walking down slopes, but large amounts results in falling too fast
  var antiBumpFactor = .75;
   
  // Player must be grounded for at least this many physics frames before being able to jump again; set to 0 to allow bunny hopping 
  var antiBunnyHopFactor = 1;
   
  private var moveDirection = Vector3.zero;
  private var grounded = false;
  private var controller : CharacterController;
  private var myTransform : Transform;
  private var speed : float;
  private var hit : RaycastHit;
  private var fallStartLevel : float;
  private var falling = false;
  private var slideLimit : float;
  private var rayDistance : float;
  private var contactPoint : Vector3;
  private var playerControl = false;
  private var jumpTimer : int;
   
  private var charHeight : float; //Initial height 
   
  function Start () {
      controller = GetComponent(CharacterController);
      myTransform = transform;
      speed = walkSpeed;
      rayDistance = controller.height * .5 + controller.radius;
      slideLimit = controller.slopeLimit - .1;
      jumpTimer = antiBunnyHopFactor;
      oldPos = transform.position;
  }
   
  function FixedUpdate() {
      var inputX = Input.GetAxis("Horizontal");
      var inputY = Input.GetAxis("Vertical");
      // If both horizontal and vertical are used simultaneously, limit speed (if allowed), so the total doesn't exceed normal move speed
      var inputModifyFactor = (inputX != 0.0 && inputY != 0.0 && limitDiagonalSpeed)? .7071 : 1.0;
   
      if (grounded) {
          var sliding = false;
          // See if surface immediately below should be slid down. We use this normally rather than a ControllerColliderHit point,
          // because that interferes with step climbing amongst other annoyances
          if (Physics.Raycast(myTransform.position, -Vector3.up, hit, rayDistance)) {
              if (Vector3.Angle(hit.normal, Vector3.up) > slideLimit)
                  sliding = true;
          }
          // However, just raycasting straight down from the center can fail when on steep slopes
          // So if the above raycast didn't catch anything, raycast down from the stored ControllerColliderHit point instead
          else {
              Physics.Raycast(contactPoint + Vector3.up, -Vector3.up, hit);
              if (Vector3.Angle(hit.normal, Vector3.up) > slideLimit)
                  sliding = true;
          }
          
          // If we were falling, and we fell a vertical distance greater than the threshold, run a falling damage routine
          if (falling) {
              falling = false;
              if (myTransform.position.y < fallStartLevel - fallingDamageThreshold && enableFallingDammage == true)
                  ApplyFallingDamage (fallStartLevel - myTransform.position.y);
                  
          }
          
          if (Input.GetKey(KeyCode.LeftShift) && enableRun == true)
          {
              speed = runSpeed;
          } 
          
          else if (Input.GetKey("c") && enableCrouch == true)
          {
              speed = crouchSpeed;
          }
          
           else
          { 
              speed = walkSpeed;
          }
  
          // If sliding (and it's allowed), or if we're on an object tagged "Slide", get a vector pointing down the slope we're on
          if ( (sliding && slideWhenOverSlopeLimit) || (slideOnTaggedObjects && hit.collider.tag == "Slide") ) {
              var hitNormal = hit.normal;
              moveDirection = Vector3(hitNormal.x, -hitNormal.y, hitNormal.z);
              Vector3.OrthoNormalize (hitNormal, moveDirection);
              moveDirection *= slideSpeed;
              playerControl = false;
          }
          // Otherwise recalculate moveDirection directly from axes, adding a bit of -y to avoid bumping down inclines
          else {
              moveDirection = Vector3(inputX * inputModifyFactor, -antiBumpFactor, inputY * inputModifyFactor);
              moveDirection = myTransform.TransformDirection(moveDirection) * speed;
              playerControl = true;
          }
   
          // Jump! But only if the jump button has been released and player has been grounded for a given number of frames
          if (!Input.GetButton("Jump"))
              jumpTimer++;
          else if (jumpTimer >= antiBunnyHopFactor) {
              moveDirection.y = jumpSpeed;
              jumpTimer = 0;
          }
      }
      else {
          // If we stepped over a cliff or something, set the height at which we started falling
          if (!falling) {
              falling = true;
              fallStartLevel = myTransform.position.y;
          }
   
          // If air control is allowed, check movement but don't touch the y component
          if (airControl && playerControl) {
              moveDirection.x = inputX * speed * inputModifyFactor;
              moveDirection.z = inputY * speed * inputModifyFactor;
              moveDirection = myTransform.TransformDirection(moveDirection);
          }
      }
   
      // Apply gravity
      moveDirection.y -= gravity * Time.deltaTime;
   
      // Move the controller, and set grounded true or false depending on whether we're standing on something
      grounded = (controller.Move(moveDirection * Time.deltaTime) & CollisionFlags.Below) != 0;
  }
   
  function Update () 
  {
  
  }
   
  // Store point that we're in contact with for use in FixedUpdate if needed
  function OnControllerColliderHit (hit : ControllerColliderHit) {
      contactPoint = hit.point;
  }
   
  // If falling damage occured, this is the place to do something about it. You can make the player
  // have hitpoints and remove some of them based on the distance fallen, add sound effects, etc.
  function ApplyFallingDamage (fallDistance : float) {
      gameObject.SendMessage("ApplyDammage", fallDistance*fallingDammageMultiplier);
      Debug.Log ("Ouch! Fell " + fallDistance + " units!");    
  }
  
  @script AddComponentMenu("CharacterPlayer/PlayerScript") 


Comment
Add comment · Show 3
10 |3000 characters needed characters left characters exceeded
â–¼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image andrew-lukasik · May 26 at 07:20 AM 0
Share


https://blog.unity.com/community/unityscripts-long-ride-off-into-the-sunset


What year is this?


avatar image DavidRoad andrew-lukasik · May 26 at 08:53 AM 0
Share

Unity 2017

avatar image andrew-lukasik · May 26 at 11:18 AM 0
Share

controller.velocity.magnitude < 7 statement causes the sound to be disabled when running

1 Reply

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by andrew-lukasik · May 26 at 10:57 AM


Welcome to the future :T


FootSteps.cs

 using UnityEngine;
 
 [RequireComponent( typeof(AudioSource) )]
 [RequireComponent( typeof(CharacterController) )]
 [AddComponentMenu( "CharacterPlayer/FootstepGrass" )]
 public class FootSteps : MonoBehaviour
 {
     public AudioClip[] ground;
     public float audioStepLengthWalk = 0.45f;
     public float audioStepLengthRun = 0.82f;
     float _nextStepTime = 0;
     bool _colliderTagCheck;
     AudioSource _audioSource;
     CharacterController _characterController;
 
     void Awake ()
     {
         _audioSource = GetComponent<AudioSource>();
         _characterController = GetComponent<CharacterController>();
     }
 
     void FixedUpdate ()
     {
         if( _colliderTagCheck && Time.time>_nextStepTime )
         {
             float speed = _characterController.velocity.magnitude;
             if( _characterController.isGrounded && speed>5 )
             {
                 _audioSource.clip = ground[ Random.Range(0,ground.Length) ];
                 _audioSource.volume = 0.1f;
                 _audioSource.Play();
                 
                 bool isRunning = Input.GetKey( KeyCode.LeftShift );
                 _nextStepTime = Time.time + ( isRunning ? audioStepLengthRun : audioStepLengthWalk );
             }
         }
     }
 
     void OnControllerColliderHit ( ControllerColliderHit hit )
     {
         _colliderTagCheck = hit.gameObject.CompareTag("Ground") || hit.gameObject.CompareTag("Grass");
     }
 
 }


PlayerScript.cs

 using UnityEngine;
 
 [RequireComponent( typeof(CharacterController) )]
 [AddComponentMenu("CharacterPlayer/PlayerScript")]
 public class PlayerScript : MonoBehaviour
 {
 
     public float walkSpeed = 6.0f;
     public float runSpeed = 11.0f;
     float crouchSpeed = 3.0f;
 
     // If true, diagonal speed (when strafing + moving forward or back) can't exceed normal move speed; otherwise it's about 1.4 times faster
     public bool limitDiagonalSpeed = true;
 
     // If checked, the run key toggles between running and walking. Otherwise player runs if the key is held down and walks otherwise
     // There must be a button set up in the Input Manager called "Run"
     public bool enableRun = true;
     public bool enableCrouch = true;
 
     public float jumpSpeed = 8.0f;
     public float gravity = 20.0f;
 
     public bool enableFallingDammage = true;
     // Units that player can fall before a falling damage function is run. To disable, type "infinity" in the inspector
     public float fallingDamageThreshold = 10.0f;
     public float fallingDammageMultiplier = 2f;
 
     // If the player ends up on a slope which is at least the Slope Limit as set on the character controller, then he will slide down
     public bool slideWhenOverSlopeLimit = false;
 
     // If checked and the player is on an object tagged "Slide", he will slide down it regardless of the slope limit
     public bool slideOnTaggedObjects = false;
 
     public float slideSpeed = 12.0f;
 
     // If checked, then the player can change direction while in the air
     public bool airControl = false;
 
     // Small amounts of this results in bumping when walking down slopes, but large amounts results in falling too fast
     public float antiBumpFactor = .75f;
 
     // Player must be grounded for at least this many physics frames before being able to jump again; set to 0 to allow bunny hopping 
     public int antiBunnyHopFactor = 1;
 
     Vector3 moveDirection = Vector3.zero;
     bool grounded = false;
     CharacterController _controller;
     Transform myTransform;
     float speed;
     float fallStartLevel;
     bool falling = false;
     float slideLimit;
     float rayDistance;
     Vector3 contactPoint;
     bool playerControl = false;
     int jumpTimer;
 
     void Start ()
     {
         _controller = GetComponent<CharacterController>();
         myTransform = transform;
         speed = walkSpeed;
         rayDistance = _controller.height * .5f + _controller.radius;
         slideLimit = _controller.slopeLimit - .1f;
         jumpTimer = antiBunnyHopFactor;
     }
 
     void FixedUpdate ()
     {
         float inputX = Input.GetAxis("Horizontal");
         float inputY = Input.GetAxis("Vertical");
         // If both horizontal and vertical are used simultaneously, limit speed (if allowed), so the total doesn't exceed normal move speed
         float inputModifyFactor = (inputX!=0f && inputY!=0f && limitDiagonalSpeed)? .7071f : 1.0f;
 
         if( grounded )
         {
             var sliding = false;
             // See if surface immediately below should be slid down. We use this normally rather than a ControllerColliderHit point,
             // because that interferes with step climbing amongst other annoyances
             RaycastHit hit;
             if( Physics.Raycast( myTransform.position , Vector3.down , out hit , rayDistance ) )
             {
                 if( Vector3.Angle(hit.normal, Vector3.up) > slideLimit)
                     sliding = true;
             }
             // However, just raycasting straight down from the center can fail when on steep slopes
             // So if the above raycast didn't catch anything, raycast down from the stored ControllerColliderHit point instead
             else
             {
                 if( Physics.Raycast( contactPoint + Vector3.up, -Vector3.up, out hit ) )
                     if( Vector3.Angle(hit.normal, Vector3.up)>slideLimit )
                         sliding = true;
             }
             
             // If we were falling, and we fell a vertical distance greater than the threshold, run a falling damage routine
             if( falling )
             {
                 falling = false;
                 if( myTransform.position.y < fallStartLevel - fallingDamageThreshold && enableFallingDammage==true)
                     ApplyFallingDamage (fallStartLevel - myTransform.position.y);
             }
             
             if( Input.GetKey(KeyCode.LeftShift) && enableRun==true)
             {
                 speed = runSpeed;
             } 
             
             else if( Input.GetKey(KeyCode.C) && enableCrouch==true)
             {
                 speed = crouchSpeed;
             }
             
             else
             { 
                 speed = walkSpeed;
             }
 
             // If sliding (and it's allowed), or if we're on an object tagged "Slide", get a vector pointing down the slope we're on
             if( ( sliding && slideWhenOverSlopeLimit ) || ( slideOnTaggedObjects && hit.collider.CompareTag("Slide") ) )
             {
                 var hitNormal = hit.normal;
                 moveDirection = new Vector3( hitNormal.x , -hitNormal.y , hitNormal.z );
                 Vector3.OrthoNormalize( ref hitNormal , ref moveDirection );
                 moveDirection *= slideSpeed;
                 playerControl = false;
             }
             // Otherwise recalculate moveDirection directly from axes, adding a bit of -y to avoid bumping down inclines
             else
             {
                 moveDirection = new Vector3( inputX * inputModifyFactor , -antiBumpFactor , inputY * inputModifyFactor );
                 moveDirection = myTransform.TransformDirection(moveDirection) * speed;
                 playerControl = true;
             }
 
             // Jump! But only if the jump button has been released and player has been grounded for a given number of frames
             if( !Input.GetButton("Jump") )
             {
                 jumpTimer++;
             }
             else if( jumpTimer>=antiBunnyHopFactor )
             {
                 moveDirection.y = jumpSpeed;
                 jumpTimer = 0;
             }
         }
         else
         {
             // If we stepped over a cliff or something, set the height at which we started falling
             if( !falling )
             {
                 falling = true;
                 fallStartLevel = myTransform.position.y;
             }
 
             // If air control is allowed, check movement but don't touch the y component
             if( airControl && playerControl )
             {
                 moveDirection.x = inputX * speed * inputModifyFactor;
                 moveDirection.z = inputY * speed * inputModifyFactor;
                 moveDirection = myTransform.TransformDirection(moveDirection);
             }
         }
 
         // Apply gravity
         moveDirection.y -= gravity * Time.deltaTime;
 
         // Move the controller, and set grounded true or false depending on whether we're standing on something
         grounded = (_controller.Move(moveDirection * Time.deltaTime) & CollisionFlags.Below)!=0;
     }
 
     // Store point that we're in contact with for use in FixedUpdate if needed
     void OnControllerColliderHit ( ControllerColliderHit hit )
     {
         contactPoint = hit.point;
     }
 
     // If falling damage occured, this is the place to do something about it. You can make the player
     // have hitpoints and remove some of them based on the distance fallen, add sound effects, etc.
     void ApplyFallingDamage ( float fallDistance )
     {
         gameObject.SendMessage( "ApplyDamage", fallDistance * fallingDammageMultiplier );
         //    ^    replcace this with a direct call, something like:
         //        HealtScript.ApplyDamage( fallDistance * fallingDammageMultiplier );
 
         Debug.Log($"Ouch! Fell {fallDistance} units!");
     }
 
 }


Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
â–¼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image DavidRoad · May 27 at 01:26 PM 0
Share

THANK YOU!

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

182 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Quaternion Roation Mouse Script 0 Answers

Cinemachine (or the unity compiler) broken due to some unknown reason 1 Answer

How important is the order of Vertices in the mesh array that the triangles point to? 0 Answers

some textures are invisible 1 Answer

Grid/TileMap rotation not affecting child GameObjects? 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges