• 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 /
avatar image
0
Question by Tuxedose · Jan 21, 2015 at 10:19 AM · 2dmovementrigidbody2dvelocity

Weird Rigidbody2D.velocity.x problem, float out of control

Hello. I have this really weird problem when using a rigidbody2D to move my character. I am programming basic RPG 4-way movement using rigidbody2D.velocity. Everything works fine and dandy except for when moving in Horizontal direction. rigidbody2D.velocity.x totally freaks out when I get to a wall with a collision2D box on it. It does not happen with the y direction at all, only the x. When I print out the velocity.x i get a number as high as: 6.658959E-08, but it only does this if I mash the right or left key when my character stands next to a colliding wall.

I cannot figure out what causes this problem, is it my code? Or is it a physics setting in Unity? My code for moving my char is below, oh and this is my first crack at this, so it is not the most beautiful solution. I have scoured it several times, but have failed to see what I have done wrong, if I have done anything wrong. :P

Thnx for the help :D

 using UnityEngine;
 using System.Collections;
 
 public class MainCharControllerScript : MonoBehaviour {
     
     public float Speed;
     //bool facingDown = true;
     //bool facingUp = false;
     bool facingRight = false;
     bool buttonCheck;
     Animator anim;
     float moveHorizontal;
     float moveVertical;
 
     Vector3 vel;
 
     
     
     // Use this for initialization
     void Start ()
         
     {
         anim = GetComponent<Animator> ();
             
     }
 
     // Update is called once per frame
     void FixedUpdate () 
         
     {
     
 
 
         //print (rigidbody2D.velocity);
         moveHorizontal = Input.GetAxis("Horizontal");
         moveVertical = Input.GetAxis ("Vertical");
 
         // check direction
         if(rigidbody2D.velocity.y == 0)
         {
             anim.SetBool ("directionUp", false);
             anim.SetBool ("directionDown", false);
         }
 
         if (rigidbody2D.velocity.x == 0) {
             anim.SetBool ("directionLeftRight", false);        
         }
 
         if (rigidbody2D.velocity.y > 0) {
             anim.SetBool ("directionUp", true);    
             anim.SetBool ("directionDown", false);
         }
 
         if (rigidbody2D.velocity.y < 0) {
             anim.SetBool ("directionDown", true);
             anim.SetBool ("directionUp", false);
         }
 
         if (rigidbody2D.velocity.x < 0 || rigidbody2D.velocity.x > 0) {
             anim.SetBool ("directionLeftRight", true);
         }
 
 
         //anim.SetInteger ("SpeedH", Mathf.Abs ((int)rigidbody2D.velocity.y));
         //anim.SetInteger ("SpeedV", Mathf.Abs ((int)rigidbody2D.velocity.x));
             
 
         print (rigidbody2D.velocity.x);
         print (rigidbody2D.velocity.y);
 
 
         //print (moveVertical);
         //rigidbody2D.velocity = new Vector2 (moveVertical * maxSpeed, rigidbody2D.velocity.x);
         
         //make sure player cannot press two directions at once
         if (Input.GetButton("Horizontal") && Input.GetButton("Vertical")) {
             buttonCheck = true;        
         }
 
 
         if (buttonCheck) {
             moveHorizontal = 0;
             moveVertical = 0;
         }
         
 
 
         if (!Input.GetButton ("Horizontal")) {
             rigidbody2D.velocity = new Vector2 (0,0);
             //anim.SetBool("WalkingLeftRight", false);
             //anim.SetBool("WalkingUpTrue", false);
             //anim.SetBool("WalkingDown", false);
                 }
 
         if (!Input.GetButton ("Vertical"))
         {
             rigidbody2D.velocity = new Vector2 (0,0);
             //anim.SetBool("WalkingUpTrue", false);
             //anim.SetBool("WalkingDown", false);
         }
 
         if(Input.GetButton("Horizontal") && Input.GetButton("Vertical") == false)
         {
             buttonCheck = false;
 
             //anim.SetBool("WalkingLeftRight", true);
 
             if(moveHorizontal > 0)
             {
                 rigidbody2D.velocity = (transform.right * Speed);
             }
 
              if(moveHorizontal < 0)
             {
                 rigidbody2D.velocity = (transform.right *- Speed);
             }
                 
             
             
             if (moveHorizontal > 0 && !facingRight) 
                 Flip ();
             else if (moveHorizontal < 0 && facingRight)
                 Flip ();
             
         }
             
 
         //anim.SetFloat ("Speed", Mathf.Abs (moveVertical));
          if (Input.GetButton ("Vertical") && Input.GetButton("Horizontal") == false) {
             buttonCheck = false;
 
 
             
             if(moveVertical > 0)
             {
                 rigidbody2D.velocity = (transform.up * Speed);
                 //anim.SetBool("WalkingUpTrue", true);
                 //anim.SetBool("WalkingDown", false);
             
             }
                 
                     
 
               if(moveVertical < 0)
                 
             {
                 rigidbody2D.velocity = (transform.up *- Speed);
                 //anim.SetBool("WalkingDown", true);
                 //anim.SetBool("WalkingUpTrue", false);
             }
 
 
             
         }
 
         
     }
 
     void OnCollisionEnter2D(Collision2D coll)
     {
         if (coll.gameObject.name == "Wall") {
             
             print ("Coll!");
             
         }
     }
     
     void Flip()
         
     {
         facingRight = !facingRight;
         Vector3 theScale = transform.localScale;
         theScale.x *= -1;
         transform.localScale = theScale;
         
     }
 
     
 }
 

 
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 sniper43 · Jan 21, 2015 at 10:35 AM 0
Share

Quick note:

 if (Input.GetButton("Horizontal") && Input.GetButton("Vertical")) {
 buttonCheck = true;
 }
 if (buttonCheck) {
 moveHorizontal = 0;
 moveVertical = 0;
 }

can be shortened to

      if (Input.GetButton("Horizontal") && Input.GetButton("Vertical")) {
  buttonCheck = true; 
     moveHorizontal = 0;
     moveVertical = 0;
     }



avatar image sniper43 · Jan 21, 2015 at 11:04 AM 0
Share

Also a note: ins$$anonymous$$d of using

  anim.SetBool ("directionDown", false);

you could create a float parameter in the Animator called DirectionVertical and have the TRANSITIONS handle the animation switches (DirectionVertical greater than/equal/less than zero), and you could shorten all teh above ifs to:

  anim.SetFloat ("directionVertical", rigidbody2D.velocity.y);

avatar image Tuxedose · Jan 21, 2015 at 11:58 AM 0
Share

Thank you for the cleanup tips sniper43. $$anonymous$$ind of hoped the cleanup would solve my problem, but it did not unfortunately. :(

I tried fiddling with the mass/drag, did not solve my problem. For some reason velocity.x still becomes an insane number. What really boggles my mind is that the velocity.y comes out perfectly fine. No -6.658959E-08 there. Just 0 when I hit a collider, even if I mash the up or down keys, (as it should).

1 Reply

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

Answer by sniper43 · Jan 21, 2015 at 11:28 AM

Your code is WAD, the E-08 6.658959E-08 is the exponent of 10 the number is multiplied by, so your number is 6.658959 * 10 to the power of -8, so it's 6.658959 / 100000000, a number so pathetically low it can be practically counted as zero.

Read through my comments and truncate your code, it'll make problem solving a lot faster. I barely scratched the surface there, on reading through your code you can probably get rid of 80% of the lines. If you're practicing coding, PLEASE exersize in truncation as your next task. It'll make problem solving easier if there's less and more logical coding.

Comment
Add comment · Show 7 · 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 sniper43 · Jan 21, 2015 at 11:12 AM 0
Share

To put a perspective here, I would've noticed the E-08 a lot sooner if I hadn't skimmed and started going through the code. I later reread it and facepalmed.

avatar image Tuxedose · Jan 21, 2015 at 01:17 PM 0
Share

Alright I will do just that. Thanks for your input :D

avatar image Tuxedose · Jan 21, 2015 at 03:15 PM 0
Share

Alright so I truncated my code according to your advice and ended up with a 69 line code ins$$anonymous$$d of 180 lines :P.

Problem still persists, only on velocity.x when colliding with something and pushing the right, as well as left, key.

Going to post the code below once again. Does it look better? Also I am beginning to believe that my float issue is not a code related one. That, or I just do not see what I am doing wrong. :P

 using UnityEngine;
 using System.Collections;
 
 public class $$anonymous$$ainCharControllerScript : $$anonymous$$onoBehaviour {
 
     public float Speed;
 
     Animator anim;
     bool facingRight = false;
     float moveHorizontal;
     float moveVertical;
 
     // Use this for initialization
     void Start ()
         
     {
         anim = GetComponent<Animator> ();
             
     }
 
     // Update is called once per frame
     void FixedUpdate () 
         
     {
 
         moveHorizontal = Input.GetAxis("Horizontal");
         moveVertical = Input.GetAxis ("Vertical");
 
         anim.SetFloat ("horizontalDirection", rigidbody2D.velocity.x);
         anim.SetFloat ("verticalDirection", rigidbody2D.velocity.y);
             
 
 
 
         if (Input.GetButton ("Horizontal") && !Input.GetButton ("Vertical")) {
 
                              if (moveHorizontal > 0){
                                 rigidbody2D.velocity = (transform.right * Speed);
                                 if (!facingRight)
                                 Flip ();
             }
                             else if (moveHorizontal < 0){
                                 rigidbody2D.velocity = (transform.right * - Speed);
                                 if(facingRight)
                                 Flip ();
             }
         
                 } else if (Input.GetButton ("Vertical") && !Input.GetButton ("Horizontal")) {
                     
                         if (moveVertical > 0)
                                 rigidbody2D.velocity = (transform.up * Speed);
                         else if (moveVertical < 0)
                                 rigidbody2D.velocity = (transform.up * - Speed);
                 } else
                         rigidbody2D.velocity = new Vector2 (0, 0);
         }
 
     void Flip()
         
     {
         facingRight = !facingRight;
         Vector3 theScale = transform.localScale;
         theScale.x *= -1;
         transform.localScale = theScale;
         
     }
 
 }
 
 
avatar image sniper43 · Jan 21, 2015 at 10:35 PM 0
Share

The value of velocity should be WAD (**W*orking As D*esigned), as in you don't need to adjust anything.

When you apply force to the right, it moves right slightly, causing you to perhaps enter the object for a couple of miliseconds for a margin relative to applied force, but it should bounce you out.

You can use a raycast to determine whetere there's a wall left/right and disable the appropriate movement, but it's not really worth the hassle.

Also again, the number formaat is different, but the number you're getting is an EXTRE$$anonymous$$ELY small one.

Clarification:

6.658959E-08

is a number written in exponential format.

First you have a float value, in this case 6.658959, then you have the E denoting an exponent, and finally the value of the exponent -08. Also note that the value left of the E is a single digit + decimals value. So it's 6 + 0.658959, not 6658959 * 10^-8

To read these values you take the float, multipy it by 10 to the power of the exponent, so in this case 6.658959 * 10^(-08).

A negative exponent means the value is the bottom part of a fraction. So multyplying by 10^(-08) means your multiplying by 1/10^8, which basically means you're dividing by 10^8.

The number you have is basically zero, but zero writen with a lot of numbers.

By comparison: 0.00000000000000000000000000000000001 isn't zero, but for all practical purpposes in code it is treated as such.

https://en.wikipedia.org/wiki/Exponentiation

By the way, good job truncating, that code is a lot more readable. Practice more, but be careful as it IS possible to truncate too much (make everythign so concise it's basically unreadable).

And as a side note, by unreadable I mean if you return to the code once in the future, the more "unreadable" your code is, the longer it'll take you or someone reviewing your script to realize what you wanted to achieve with each line of code, and the entirety of the code.

avatar image sniper43 · Jan 21, 2015 at 10:37 PM 0
Share

Final note: the velocity should NOT be zero if you are moving, but if you are moving into a wall, the force should be near enough to zero.

What happens is that force is applied, then removed gradually. The gradual removal is what's causign you to see the low float value.

Show more comments

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.

Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.



Follow this Question

Answers Answers and Comments

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

How do I make my character's movement less floaty? 1 Answer

Make an object that moves relative to the touch more natural 0 Answers

Dashing with rigidbody2D not working right 2 Answers

can't move player rigidbody.velocity 1 Answer

Rigidbody2D x velocity not moving unless placed in FixedUpdate 1 Answer

  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges