c# - 当我使用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));
}
}
解决方案
你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));
}
}
推荐阅读
- java - 我必须编写一个方法来确定游戏中何时不能有赢家(平局)
- python - 为什么我能够在 Pytorch 中使用 detach 来更改张量的值而计算图不知道它?
- flutter - 为什么 toDouble 和 toInt 在我的项目中不起作用
- javascript - 获取选择选项以使用 JavaScript 显示隐藏内容
- javascript - 如何迭代对象中的特定键?
- reactjs - 弹出框组件不尊重样式属性
- r - 将列表合并到 R 中的一个列表中
- javascript - 测试库 React Native
- typescript - RXJS Angular - 使用 .subscribe 和 Observable 处理错误
- r - 在R中创建列联表