C# 如何向rigidbody2d游戏对象添加随机方向的力
如何向rigidbody2D游戏对象添加力并使其以固定速度移动?游戏对象还附加了反弹材质C# 如何向rigidbody2d游戏对象添加随机方向的力,c#,unity3d,C#,Unity3d,如何向rigidbody2D游戏对象添加力并使其以固定速度移动?游戏对象还附加了反弹材质 private Rigidbody2D rb2D; private float thrust = 10.0f; void Start() { } void FixedUpdate() { rb2D.AddForce(new Vector2(0, 1) * thrust); } 这是我从Unity documentations网站上得到的,但这似乎没有任何作用 这是我最后使用的
private Rigidbody2D rb2D;
private float thrust = 10.0f;
void Start() {
}
void FixedUpdate() {
rb2D.AddForce(new Vector2(0, 1) * thrust);
}
这是我从Unity documentations网站上得到的,但这似乎没有任何作用
这是我最后使用的代码,它似乎运行正常。矢量2的方向和速度可以根据质量/重力进行调整
float topSpeed = 15;
private Rigidbody2D rb2D;
private float thrust = 0.1f;
void Start()
{
rb2D = gameObject.GetComponent<Rigidbody2D>();
rb2D.AddForce(new Vector2(0, 1) * thrust);
}
void Update()
{
if (rb2D.velocity.magnitude > topSpeed || rb2D.velocity.magnitude < topSpeed)
rb2D.velocity = rb2D.velocity.normalized * topSpeed;
}
float-topSpeed=15;
私有刚体2d rb2D;
专用浮子推力=0.1f;
void Start()
{
rb2D=gameObject.GetComponent();
rb2D.附加力(新矢量2(0,1)*推力);
}
无效更新()
{
if(rb2D.velocity.magnitude>topSpeed | | rb2D.velocity.magnitude
编写的代码一旦生效,将无限加速刚体。您需要将速度限制在其最大速度:
如果希望它立即将速度设置为固定值,则可以在每一帧上设置速度:
您的代码没有显示它,因此,如果您还没有执行此操作,您需要确保rb2D
在要操作的对象上实际设置为Rigidbody2d。例如,通过在启动方法中执行:
void Start()
{
rb2D = gameObject.GetComponent<Rigidbody2D>();
}
void Start()
{
rb2D=gameObject.GetComponent();
}
void FixedUpdate()
{
if (Input.GetButtonDown("Jump"))
{
// the cube is going to move upwards in 10 units per second
rb2D.velocity = new Vector3(0, 10, 0);
moving = true;
Debug.Log("jump");
}
if (moving)
{
// when the cube has moved over 1 second report it's position
t = t + Time.deltaTime;
if (t > 1.0f)
{
Debug.Log(gameObject.transform.position.y + " : " + t);
t = 0.0f;
}
}
}
void Start()
{
rb2D = gameObject.GetComponent<Rigidbody2D>();
}