I have 1 year experience of coding in C++, but just yesterday i've started learning Unity.I saw it needs C# so this won't be too different.Right now, I am trying to move a 2d object, but i really want to understand how it works and not just copy some lines of code.So, this is how they do it:
//
float horizontal = Input.GetAxis("Horizontal");
//which i assume gets the x coordonate of my object;
myRigidBody.velocity = new vector2(horizontal , myRigidBody.velocity.y);
//
And i don't think i get the idea of this code.I read that velocity takes 2 values (x,y) but i am not quite sure what it is doing with them.And getAxis takes a value from [-1,1] which i also don't understand.If you could help me i'd be grateful.
Input.GetAxis("Horizontal");
returns the current value for the axis named Horizontal
as defined in Unity's Input manager.
Also, new vector2(horizontal, myRigidBody.veloicty.y);
is probably a typo, because the type of Rigidbody.velocity
is Vector3
. And Vector2
is an object that has an implicit conversion to Vector3
.
Anyway, myRigidBody.velocity = new Vector2(horizontal, myRigidBody.velocity.y);
creates an instance of a Vector2
type where the x component is horizontal
, and the y component is the current y component of the rigidbody's velocity, and then it assigns that Vector2
to the rigidbody's velocity.
GetAxis("Horizontal") returns the values from left (-1,0,0) and right (1,0,0) when you press the arrows keys. Anyway, you'll get the values interpolated and not a sudden change. Try the code below and see how it looks on the inspector
public float horizontal;
private void Update()
{
horizontal = Input.GetAxis("Horizontal");
}
As for the velocity, you "force change" the velocity of the rigidbody in any direction you want x,y (horizontal,vertical axis). You can also multiply your axis values with a speed variable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.