我是Unity和C#的新手。我试图编写2D平台游戏移动脚本的代码,但是由于某些原因,我正在创建的代码无法正常工作。
该脚本称为圆。我添加了“ Rigidbody2D”和“ Circle Collider 2D”。
我尝试使用此脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public Rigidbody2D rb;
public void FixedUpdate()
{
if (Input.GetKey(KeyCode.RightArrow))
{
rb.AddForce(10, 0, 0);
}
}
}
该代码应该对圆进行敲击以使其向右移动,但是Visual Studio说“ rb.AddForce”是一个错误。你能帮我吗?
答案 0 :(得分:4)
您确定您实际上已经引用了刚体吗?您是否在编辑器中拖动了刚体?如果没有,您也可以说以下内容(如果脚本附加到了要移动刚体的对象上):
private Rigidbody2D rb;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
1)确保未将Rigidbody组件设置为Kinematic。
2)根据刚体的质量和线性阻力,您需要相应地更改对其施加的力。该代码可能有效,但是如果没有施加足够的力,您将看不到身体在运动。
3) Addforce()需要一个 Vector 作为参数。这是您的问题。
public float thrust; //set in editor, this is how strong you will be pushing the object
private Rigidbody2D rb;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
if (Input.GetKey(KeyCode.RightArrow))
{
rb.AddForce(transform.right * thrust); //this will move your RB to the right while you hold the right arrow
}
}
4)设置刚体的线性阻力,以使其在施加力后实际上可以停止。为了使其工作,例如将质量和线性阻力都设置为1,然后仅对推力变量进行试验,最终它将开始移动。之后,您可以减小/增加线性阻力和推力,直到获得理想的效果。
奖金 如果您希望以在代码中尝试过的方式使用Vector3D,则可以执行以下操作,它也将起作用:
private void FixedUpdate()
{
if (Input.GetKey(KeyCode.RightArrow))
{
rb.AddForce(new Vector3(10, 0, 0)); //this will move your RB to the right while you hold the right arrow
}
}
答案 1 :(得分:0)
由于采用Rigidbody2D,因此在构造函数中使用Vector2作为参数,而不是可以将Vector3和Vector2作为Vector3的简单Rigidbody。考虑Vector3 v3 = new Vector2(10, 0);
,然后
Vector2 v2 = new Vector3(10, 0, 0);
尝试一下
rb.AddForce(new Vector2(10, 0));
或
rb.AddForce(new Vector3(10, 0, 0));
答案 2 :(得分:0)
您需要添加ForceMode2D.Impulse使其起作用:
"kubectl apply -f projectname.json"
您可以在此处找到更多信息:https://www.studytonight.com/game-development-in-2D/right-way-to-move