- Home /
Question by
UnityCub · Oct 07, 2018 at 07:01 PM ·
rigidbody2dvelocityplatformerrigidbody.velocity
Updated version of Rigidbody2D.velocity?
I'm new to Unity and working on a platformer, and I'm using the code below for testing the movement at the moment. As you can see, the vector that controls the jump should have an argument that takes the player's current x velocity instead of 0.
I have watched some tutorial videos which all used Rigidbody2D.velocity.x to get the x velocity of the object, but this is outdated and was used in Unity 4.
For Unity 5, what is the equivalent of Rigidbody2D.velocity that can be used as an argument in the vector?
void Update () {
if(Input.GetKeyDown(KeyCode.UpArrow))
{
GetComponent<Rigidbody2D>().velocity = new Vector2(0, jumpHeight);
}
if (Input.GetKey(KeyCode.LeftArrow))
{
GetComponent<Rigidbody2D>().velocity = new Vector2(-1*moveSpeed, 0);
}
if (Input.GetKey(KeyCode.RightArrow))
{
GetComponent<Rigidbody2D>().velocity = new Vector2(moveSpeed, 0);
}
}
}
Comment
Answer by sanja15513 · Oct 07, 2018 at 07:44 PM
Rigidbody2D rb;
public float speed = 10f;
public float jumpHeight = 5f;
float movement = 0;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
movement = Input.GetAxis("Horizontal") * speed;
}
void FixedUpdate()
{
Vector2 velocity = rb.velocity;
velocity.x = movement;
if (Input.GetKeyDown(KeyCode.UpArrow))
{
velocity.y = jumpHeight;
}
rb.velocity = velocity;
}
Maybe something like this?
Your answer
![](https://koobas.hobune.stream/wayback/20220612175937im_/https://answers.unity.com/themes/thub/images/avi.jpg)