play sound when rigid body speed is greater than 1

im trying to make a script in which if the rigidbody2d (the player) speed is greater than 0 it will play a footstep sound effect but it doesn’t seem to be working. i used debug.log and it wasn’t the fault of the sound, so its something wrong with detecting if the player is moving or not.

if (player.velocity.magnitude >= 0.01 && playeraudio.isPlaying == false){
            playeraudio.PlayOneShot(woodwalk);
            Debug.Log ("sound");
        }

So did you debug.log player.velocity.magnitude?

I put the debug.log in the if statement of the function

Well what is its velocity then? Try debugging that. It’s also shown in the Inspector for the Rigidbody2D if you open the “Info” fold-out.

Note that if you’re just modifying the Transform then it has no velocity as it is just instantly set to a new position. Or if you’re using MovePosition, this too doesn’t modify the velocity.

Only adding forces (which modify the velocity) or gravity or directly setting the velocity modifies velocity.

Note that “0.01” is a double, you should use “0.01f”.

That’s not useful.

Put it BEFORE the if statement so you can see what value it is.

Better yet, untangle that horrible mess of an if statement and let it breathe!

Assign the magnitude to a temporary variable, print it out, then test that variable in the if statement.

If you have more than one or two dots (.) in a single statement, you’re just being mean to yourself.

How to break down hairy lines of code:

http://plbm.com/?p=248

Break it up, practice social distancing in your code, one thing per line please.

You must find a way to get the information you need in order to reason about what the problem is.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

https://discussions.unity.com/t/839300/3

@Henrymon Before your if statement, try placing the following:

Debug.Log("Magnitude = " + player.velocity.magnitude.ToString());
Debug.Log("Playing = " + playeraudio.isPlaying.ToString());

Then perhaps a few more Debug.Log statements through all your code. Then provide your updated code along with the console output.

1 Like

i realize now that im using move position so it doesnt modify the velocity. what could i do if it doesnt detect velocity.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class playeranim : MonoBehaviour{
    public float moveSpeed = 5f;
   
    public Animator animator;
    public Rigidbody2D player;
    public AudioSource playeraudio;
    public AudioClip woodwalk;

    Vector2 movement;
    void Start(){
        player = GetComponent<Rigidbody2D>();
        animator = GetComponent<Animator>();
    }



    // Update is called once per frame
    void Update()
    {
        Vector3 movement = new Vector3(Input.GetAxis("Horizontal"),Input.GetAxis("Vertical"),0.0f);

        animator.SetFloat("Horizontal", movement.x);
        animator.SetFloat("Vertical", movement.y);
        animator.SetFloat("Magnitude", movement.magnitude); 
        movement = movement.normalized;

        transform.position = transform.position + movement * Time.deltaTime;     
    }
    void FixedUpdate(){
        if (player.velocity.magnitude >= 0.01f && playeraudio.isPlaying == false){
            playeraudio.PlayOneShot(woodwalk);
            Debug.Log ("sound");
        }
    }
}

Looks to me like you’re modifying the Transform and NOT using MovePosition which is even worse.

It’s an odd question. It does detect velocity, it doesn’t need fixing. The velocity is zero!

It just sounds like you want to know if it’s moved at all. You are “moving” it here, you even set the magnitude of that movement to the animator so use that value.

1 Like

Please add appropriate Debug.Log statements to show us what you mean.