如何做 rb.添加力量,但用于 2D?团结 C#



我正在制作一个2D游戏,你控制一个盾牌,你必须阻止掉落的障碍物到达基地。我知道要移动你用的东西rb.addforce.但是,当我对 2D 执行相同的操作时,它不起作用。我想不是使用 Vector3,而是使用 Vector2,但它给了我以下 2 个错误:AssetsMovement.cs(16,25): error CS1503: Argument 1: cannot convert from 'float' to 'UnityEngine.Vector2'和这个:每次我写行时都会AssetsMovement.cs(16,25): error CS1503: Argument 1: cannot convert from 'float' to 'UnityEngine.Vector2'。这是我的完整代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public Rigidbody2D rb;
public Collider2D collider;
public float moveSpeed = 0.1f;
private void Update() 
{
if (Input.GetKey("w"))
{
rb.AddForce(0f, moveSpeed);
Debug.Log("w");
}
if (Input.GetKey("s"))
{
rb.AddForce(0f, moveSpeed);
Debug.Log("s");
}
}
}

您可以在rb.AddForce (new Vector2(0,moveSpeed));中添加新Vector2

以下是更新的代码:

public class Movement : MonoBehaviour
{
public Rigidbody2D rb;
public Collider2D collider;
public float moveSpeed = 0.1f;
private void Update()
{
if (Input.GetKey("w"))
{
rb.AddForce(new Vector2(0f, moveSpeed));
Debug.Log("w");
}
if (Input.GetKey("s"))
{
rb.AddForce(new Vector2 (0f, moveSpeed));
Debug.Log("s");
}
}
}

Rigidbody2D.AddForce不需要两个float参数,而是像往常一样接受一个Vector2和一个ForceMode2D,如果你不传入,后者的默认值为ForceMode2D.Force

所以你的代码应该是

//          = new Vector2 (0,1) * moveSpeed
//          = new Vector2 (0, moveSpeed)
rb.AddForce(Vector2.up * moveSpeed);
...
// I assume in the second case you rather want to go down so
//           = new Vector2 (0, -1) * moveSpeed
//           = new Vector2 (0, -moveSpeed)
rb.AddForce(Vector2.down * moveSpeed);

顺便说一句,我宁愿不Debug.Log每一帧Update它非常昂贵。

相关内容

  • 没有找到相关文章

最新更新