当我使用rigidbody2D.velocity.y时出现语法错误

时间:2018-09-16 05:13:40

标签: c# unity3d syntax-error unityscript

我正在写我的第一个游戏,以及教我角色跳跃的代码。我遇到此错误“ rigidbody2D.velocity.y”和“ rigidbody2D.AddForce”用红色下划线标出,我不明白为什么。

我的代码:

private bool isGrounded = false;
public Transform groundCheck;
private float groundRadius = 0.2f;
public LayerMask whatIsGround;
private Animator anim;

private void Start()
{
    anim = GetComponent<Animator>();
}

private void FixedUpdate()
{
    isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround);

    anim.SetBool("Ground", isGrounded);
    anim.SetFloat("vSpeed", rigidbody2D.velocity.y);

    if (!isGrounded)
        return;
}


private void Update()
{
    if (isGrounded && Input.GetKeyDown(KeyCode.Space))
    {
        anim.SetBool("Ground", false);
        rigidbody2D.AddForce(new Vector2(0, 600));
    }
}

1 个答案:

答案 0 :(得分:1)

您的游戏对象必须具有 Rigidbody2D 组件,并且您必须首先以类似启动方法的方式获得 Rigidbody2D component 这个:

...
private Rigidbody2D rigidbody2D;

void Start()
{
    ...
    rigidbody2D = GetComponent<Rigidbody2D>();
}

然后访问Rigidbody2D属性。

修改后的代码:

private bool isGrounded = false;
public Transform groundCheck;
private float groundRadius = 0.2f;
public LayerMask whatIsGround;
private Animator anim;
private Rigidbody2D rigidbody2D;

private void Start()
{
    anim = GetComponent<Animator>();
    rigidbody2D = GetComponent<Rigidbody2D>();
}

private void FixedUpdate()
{
    isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround);

    anim.SetBool("Ground", isGrounded);
    anim.SetFloat("vSpeed", rigidbody2D.velocity.y);

    if (!isGrounded)
        return;
}


private void Update()
{
    if (isGrounded && Input.GetKeyDown(KeyCode.Space))
    {
        anim.SetBool("Ground", false);
        rigidbody2D.AddForce(new Vector2(0, 600));
    }
}