Hey can someone explain me the coding

please can someone explain me as simple as possible the ‘‘Vector2’’ and ‘’.velocity’’
I got 0 experience in code so its really hard for me to understand

Vector2 is a struct that holds two float variables, x and y


Edit: I must have deleted part of my reply by accident…
velocity is a variable inside the RigidBody2D class and it’s declared as a Vector2
If you want to assign a value directly to it you have to give it a Vector2 to match
This is why you’re making a new Vector2 to input your values

Alternatively, you could access the x and y floats and assign them individually like so

void Update()
{
    myRigidbody.velocity.x = moveSpeed;
    myRigidbody.velocity.y = 0f;
}

If you’re struggling with these concepts then I would suggest you take the C++ Fundamentals course first, it’s not Unity related but it covers basic programming concepts that will help you regardless what language you’ll program in later.

1 Like

Ok, so lets start with .velocity.
I guess you know what is velocity, so the . before it means, it is specific property of myRigidbody. Because myRigidbody is of type Rigidbody2D, myRigidbody.velocity describes speed of your object in 2D space. And it requires 2 values representing speed of your rigidbody in 2 dimentions (left/right, up/down)

I don’t know how far back we need to go with theory here, but lets assume complete beginning.
You can describe 2D space as a set of coordinates in 2 dimensions - they are called X and Y coordinates (X for left and right, Y for top to bottom). Every point in that space can be shown as a set of 2 values - For example 0x, 0y is the center of the world. That set of values can be called a Vector, and to be precise, a Vector2 (you can have vectors with more dimensions, like 3D vectors for 3D world space).

So a Vector2 is in its simplest form just a set of 2 values. In this example it is used to describe speed of your object in 2D space, with X (left/right) being 1 and Y (up/down) being 0, which means the object moves to the right with the speed (velocity) of 1 unit.
You can obviously check the wikipedia for Vector (maths physics) and Carthesian Coordinate system if this needs more clarification.

3 Likes

Actually, you can’t. The velocity is a Vector2 and Vector2 is a struct. You cannot update the members of a struct property like that. You need to get the velocity out, update the values and then put it back

void Update()
{
    Vector2 velocity = myRigidbody.velocity;
    velocity.x = moveSpeed;
    velocity.y = 0f;
    myRigidbody.velocity = velocity;
}
1 Like

@bixarrio Maybe I need that C++ Fundamentals course too. It’s the 2nd time I made this mistake…

Lol, not big deal. We all make mistakes like that. I just remember because I’ve done it so many times myself.

Thanks

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms