简体   繁体   English

移动二维 object 统一

[英]moving 2d object unity

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:我在 C++ 有 1 年的编码经验,但就在昨天我开始学习 Unity。我看到它需要 C# 所以这不会太不同。现在,我正在尝试移动 2d ZA8CFDE63311BD59EB2AC96B6 但8了解它是如何工作的,而不仅仅是复制一些代码行。所以,这就是他们的做法:

//
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.而且我不认为我明白这段代码的想法。我读到速度需要 2 个值 (x,y) 但我不太确定它对它们做了什么。getAxis 从 [-1,1 中获取一个值] 我也不明白。如果你能帮助我,我将不胜感激。

Input.GetAxis("Horizontal"); returns the current value for the axis named Horizontal as defined in Unity's Input manager.返回 Unity 输入管理器中定义的名为Horizontal的轴的当前值。

Also, new vector2(horizontal, myRigidBody.veloicty.y);此外, new vector2(horizontal, myRigidBody.veloicty.y); is probably a typo, because the type of Rigidbody.velocity is Vector3 .可能是一个错字,因为Rigidbody.velocity的类型是Vector3 And Vector2 is an object that has an implicit conversion to Vector3 . Vector2是一个 object , 它隐式转换为Vector3

Anyway, myRigidBody.velocity = new Vector2(horizontal, myRigidBody.velocity.y);无论如何, 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.创建一个Vector2类型的实例,其中 x 分量是horizontal的,y 分量是刚体速度的当前 y 分量,然后将Vector2分配给刚体的速度。

GetAxis("Horizontal") returns the values from left (-1,0,0) and right (1,0,0) when you press the arrows keys.当您按下箭头键时,GetAxis("Horizontal") 从左侧 (-1,0,0) 和右侧 (1,0,0) 返回值。 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).至于速度,您可以“强制改变”刚体在任何您想要的 x,y 方向(水平、垂直轴)上的速度。 You can also multiply your axis values with a speed variable.您还可以将轴值与速度变量相乘。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM