首页 > 解决方案 > 当我使用rigidbody2D.velocity.y 时出现语法错误

问题描述

我正在编写我的第一个游戏,以及教我的角色跳跃的代码。我遇到了这个错误“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));
    }
}

标签: c#unity3dsyntax-error

解决方案


Game Object必须有一个Rigidbody2D 组件,你应该首先得到Rigidbody2D 组件start method

...
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));
    }
}

推荐阅读