// this first line constructs a Vector3 that looks like this: [X, 0, Z]
// (X and Z are our inputs multiplied by movement speed)
Vector3 vel = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")) * _speed;
// here we replace the middle zero with the Rigidbody's original velocity
// (this means we are only changing the X and Z components of the velocity,
// and the Y (up/down) component is preserved)
vel.y = _rb.velocity.y;
// assign velocity to Rigidbody
_rb.velocity = vel;
I would personally express this code more like this:
var velocity = _rb.velocity;
_rb.velocity = new Vector3(
x: Input.GetAxis("Horizontal") * _speed,
y: velocity.y, // y is unchanged
z: Input.GetAxis("Vertical") * _speed
);
And soon-ish, when Unity updates their supported C# lang version🙏, you’ll be able to do it like this:
_rb.velocity = _rb.velocity with
{
x = Input.GetAxis("Horizontal") * _speed,
z = Input.GetAxis("Vertical") * _speed,
};
It may be helpful to you to start with some basic C# tutorials so you understand what these simple statements are doing.
In the case of the first line it is doing THREE things:
reading X and Y input
making a Vector3 named vel out of the input
scaling it by speed.
Tutorials that cram all that in one line are doing you a disservice by confusing what is going on.
The second line is injecting the y component of the rigidbody int your vel vector.
The third line is assigning the vel vector back to the rigidbody’s .velocity field
When you understand the parts involved that I just listed above you will understand the answers to your questions.
Meanwhile, I suggest trying this decompositional approach:
Imphenzia: How Did I Learn To Make Games:
IMNSHO, the absolute LAST thing we need is new syntactic sugar that can only be used on extremely-recent versions of Unity confusing new users to the system. That’s not a helpful thing at all to anybody on this entire planet.
I’m completely tired of people stuck writing C# 3.0 code their whole lives for some vague reason that allegedly has to do something with compatibility or not scaring the newbies. It’s a lazy excuse. Unity devs should absolutely be getting exposed to perfectly readable, years old features of the language they’re using, instead of treating each other like children incapable of handling a little with { }.
And yet every day we have several posts right in this forum from people who have used these crazy constructs to pack 27 different statements into a single statement 300+ characters long with 47 dots in it.
“I have this weird NullReferenceException error that I just can’t figure out!”
Looking up I see this post flagged as “Beginner” so I’m thinking simple-simple-simple. I stand by that.