- Home /
Why does this piece of code work with gravity and this one dosent
Hey i working with this code for movement it works the way i want to except for jumping. My player, when he jumps goes through an instant jump upwards and a slow decent. I have found the problem in my basic movement code but i don't get why its doing what it does. The commented out piece works with gravity but the other one dosen't. can you help explain why this is and give me a solution if possible?
moveVelocity = moveSpeed * (Input.GetAxisRaw ("Horizontal"));
//myRigidbody2D.velocity = new Vector2 (moveVelocity * transform.right.x, myRigidbody2D.velocity.y);
myRigidbody2D.velocity = transform.right * moveVelocity;
Answer by Rostam24 · Sep 26, 2015 at 08:24 PM
When I changed every rigidbody in my game to rigidbody2d, I had the same problem. Eventually, I ended up using rigidbody2d.AddForce for everything. Setting velocity or moveposition in one place would overwrite what I did in other places. I have no idea why that happened (I'm still pretty new to Unity), but using addforce was the solution for me.
um that dosent work because add force will continue to speed up over time
You'll need to set some kind of maxspeed and check for that before doing addforce. I just shared my code in another answer, you could take a look at it for ideas: http://answers.unity3d.com/questions/1072298/simulating-fighter-jet-physics-with-addforce.html
Answer by cjdev · Sep 27, 2015 at 06:19 AM
In the first commented line you are moving in both the x-axis, by 'moveVelocity' units to the right, and in the y-axis, by your Rigidbody y-velocity (gravity).
In the second line you are moving only in the x-axis to the right at a speed of 'moveVelocity' units. There's no y-axis movement involved so you aren't going to see any effect from gravity. Try adding in the Rigidbody's y-velocity to the second one to account for gravity again.
I put in myRigidbody2D.velocity = transform.right moveVelocity myRigidbody2D.velocity.y; and my character didnt move unless i jumped and when i did it went crazy
Your answer
Follow this Question
Related Questions
How do I make a character Lunge? 2 Answers
Can someone help me with this Rigidbody2D bug? 1 Answer
I want to move the player once while he is jumping 1 Answer
Simple Rigidbody2D movement and jump 0 Answers