Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Resolved Rigidbody velocity value changes to negative when the object is rotated 180 degrees

Discussion in 'Scripting' started by harsha_kr, Oct 11, 2023.

  1. harsha_kr


    Mar 30, 2020
    I'm using this simple code to move the object using its rigidbody

    thisRb.velocity = transform.forward * speed;

    when the object rotation is set to 0 everything works as intended, but when I rotate the object 180 degree the rigidbody.velociy.z component turns negative, this is in turn affecting some other calculations in other parts of the code. for example i was setting a bool flag to see if the object is moving by checking if the velocity.z is greater than 0, when the velocity.z becomes negative this flag changes to false(i do have a work around for this problem) I want to understand more on why this happens and how I can deal with this in future.

    Also How can i keep the rigidbody velocity always positive regardless of the object orientation.

    any help is appreciated. Thanks in advance.
  2. Kurt-Dekker


    Mar 16, 2013
    changes when you rotate around.

    If you want it to go forever forward in the world, try
    , like this:

    Code (csharp):
    1. thisRb.velocity = Vector3.forward * speed;
    Deleted User likes this.
  3. harsha_kr


    Mar 30, 2020
    Hey Kurt, Thank you for your response. Yeah I tried that but as you said the gameobject always moves in world z direction(forward) regardless of its rotation. I need it to always move in its local forward direction.
  4. Kurt-Dekker


    Mar 16, 2013
    That's what you had originally, assuming you were considering the correct Transforms / Rigidbodies.

    Find out if you were!

    Time to start debugging! Here is how you can begin your exciting new debugging adventures:

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

    Once you understand what the problem is, you may begin to reason about a solution to the problem.

    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
    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 names of the GameObjects or Components involved?
    - 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.

    You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as

    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.

    Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer for iOS: or this answer for Android:

    If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

    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.

    If your problem is with OnCollision-type functions, print the name of what is passed in!

    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:

    "When in doubt, print it out!(tm)" - Kurt Dekker (and many others)

    Note: the
    function is an alias for Debug.Log() provided by the MonoBehaviour class.
    harsha_kr likes this.
  5. kdgalla


    Mar 15, 2013
    Velocity is working exactly like it's supposed to. If you move in a direction that is negative, then you have a negative velocity. This is correct. It's your "other calculations" that are wrong.

    What you really want is the velocity.magnitude. That's what most people think of as the "speed" that an object is moving in. If you're only interested in the z component, you can just take the absolute value.
    Last edited: Oct 11, 2023
    harsha_kr, Bunny83 and Kurt-Dekker like this.
  6. harsha_kr


    Mar 30, 2020
    Thank you both Kurt and Kdgalla for your responses.

    I think I confused everyone with my initial question(to be honest even i was confused) I'm sorry about that.

    Here is another scritp i wrote to dig deaper

    using UnityEngine;

    public class TestVector : MonoBehaviour
    Rigidbody thisRb;

    Vector3 velocityVector=;
    void Start()
    thisRb = this.gameObject.GetComponent<Rigidbody>();
    velocityVector.z = 10;
    void Update()
    thisRb.velocity = velocityVector;

    My understanding of this script is the Rigidbody should always move in its local z direction as im setting velocityVector.z = 10; regardless of its rotation.

    even all the research I did and Chat GPT says it should move in its local z direction:(this is what i got from chat gpt)
    "The Rigidbody.velocity property is calculated based on the object's local space, not world space. When you set the velocity of a Rigidbody using Rigidbody.velocity, you are specifying the speed and direction of the object's movement in its own local coordinate system.

    This means that if you set rigidbody.velocity to new Vector3(0, 0, 10), the object will move forward along its local z-axis, regardless of its current rotation or the global world coordinates."

    But when I attach this same script to a cube(newly createad without any additional scritpts attached) for some reason the cube always moves in the world z(positive) direction even if it is rotated.

    I just cant wrap my head around this. I'm sorry if I'm not making sense :(

    I have added a video of this in:
  7. spiney199


    Feb 11, 2021
    Well Chat GPT is just outright wrong there (big surprise).
    is world-space. You're better off working off the documentation than the chat bot:

    If something is local it's generally always preceed with 'local'. Such as
    , etc.

    If you want a rigidbody to always travel to "its right", then you would send it in the direction of its
    property, which is a world-space direction that points to an object's 'right' based on its rotation. It's really just
    Vector3.right * transform.rotation

    Keep in mind that, 'world-space' and 'local-space' depend on the frame of reference. A
    value can be both at the same time, it just depends what context you use it in.
    harsha_kr, Bunny83 and Harry-Wells like this.
  8. Kurt-Dekker


    Mar 16, 2013
    Abandon chat GPT... it is not even REMOTELY correct here, as Spiney points out. It is literally telling you the wrong thing. Wrong, wrong, wrong. Never go back there. Just ... don't.

    Instead, free your mind by only reading source documentation for things you are trying to use. If you feel lost, try this iterative one-thing-at-a-time approach:

    Imphenzia: How Did I Learn To Make Games:

    Tutorials and example code are great, but keep this in mind to maximize your success and minimize your frustration:

    How to do tutorials properly, two (2) simple steps to success:

    Step 1. Follow the tutorial and do every single step of the tutorial 100% precisely the way it is shown. Even the slightest deviation (even a single character!) generally ends in disaster. That's how software engineering works. Every step must be taken, every single letter must be spelled, capitalized, punctuated and spaced (or not spaced) properly, literally NOTHING can be omitted or skipped.

    Fortunately this is the easiest part to get right: Be a robot. Don't make any mistakes.

    If you get any errors, learn how to read the error code and fix your error. Google is your friend here. Do NOT continue until you fix your error. Your error will probably be somewhere near the parenthesis numbers (line and character position) in the file. It is almost CERTAINLY your typo causing the error, so look again and fix it.

    Step 2. Go back and work through every part of the tutorial again, and this time explain it to your doggie. See how I am doing that in my avatar picture? If you have no dog, explain it to your house plant. If you are unable to explain any part of it, STOP. DO NOT PROCEED. Now go learn how that part works. Read the documentation on the functions involved. Go back to the tutorial and try to figure out WHY they did that. This is the part that takes a LOT of time when you are new. It might take days or weeks to work through a single 5-minute tutorial. Stick with it. You will learn.

    Step 2 is the part everybody seems to miss. Without Step 2 you are simply a code-typing monkey and outside of the specific tutorial you did, you will be completely lost. If you want to learn, you MUST do Step 2.

    Of course, all this presupposes no errors in the tutorial. For certain tutorial makers (like Unity, Brackeys, Imphenzia, Sebastian Lague) this is usually the case. For some other less-well-known content creators, this is less true. Read the comments on the video: did anyone have issues like you did? If there's an error, you will NEVER be the first guy to find it.

    Beyond that, Step 3, 4, 5 and 6 become easy because you already understand!

    Finally, when you have errors, don't post here... just go fix your errors! Here's how:

    The complete error message contains everything you need to know to fix the error yourself.

    The important parts of the error message are:

    - the description of the error itself (google this; you are NEVER the first one!)
    - the file it occurred in (critical!)
    - the line number and character position (the two numbers in parentheses)
    - also possibly useful is the stack trace (all the lines of text in the lower console window)

    Always start with the FIRST error in the console window, as sometimes that error causes or compounds some or all of the subsequent errors. Often the error will be immediately prior to the indicated line, so make sure to check there as well.

    Look in the documentation. Every API you attempt to use is probably documented somewhere. Are you using it correctly? Are you spelling it correctly? Are you structuring the syntax correctly? Look for examples!

    All of that information is in the actual error message and you must pay attention to it. Learn how to identify it instantly so you don't have to stop your progress and fiddle around with the forum.

    Remember: NOBODY here memorizes error codes. That's not a thing. The error code is absolutely the least useful part of the error. It serves no purpose at all. Forget the error code. Put it out of your mind.
    harsha_kr likes this.
  9. harsha_kr


    Mar 30, 2020
    Thank you Spiney and Kurt You guys are legends <3
    Man I read the description of rigidbody.velocity unity API page more than 10 times but never noticed the note. What an idiot:D:D:D

    Really appreciate your help. Will try not to use it again.

    Also this is really interesting
    Thank you Spiney <3
    And Kurt the tips you gave are just awesome. Thanks man. You are the best <3
    Last edited: Oct 26, 2023
    Kurt-Dekker likes this.