C# 刚体中的AddForce完全不工作
我一直在遵循指南,我一直在几十个论坛中跋涉,随后,我一直在扯掉我剩下的头发 正如你在代码中看到的,我试图用速度来做运动,用加力来做跳跃运动。如果我使用速度,它跳得非常快,达到最大值,我只是不希望发生这种情况。我想要一个平滑的跳跃,更真实,所以我看到它说使用AddForce代替。除了这根本不起作用,他只是现在不跳了。。。没什么 我以速度工作。代码是 rb.速度=跳跃*跳跃力 正如我所说,这是可行的,但它跳得太快了,看起来一点都不正确C# 刚体中的AddForce完全不工作,c#,unity3d,2d,C#,Unity3d,2d,我一直在遵循指南,我一直在几十个论坛中跋涉,随后,我一直在扯掉我剩下的头发 正如你在代码中看到的,我试图用速度来做运动,用加力来做跳跃运动。如果我使用速度,它跳得非常快,达到最大值,我只是不希望发生这种情况。我想要一个平滑的跳跃,更真实,所以我看到它说使用AddForce代替。除了这根本不起作用,他只是现在不跳了。。。没什么 我以速度工作。代码是 rb.速度=跳跃*跳跃力 正如我所说,这是可行的,但它跳得太快了,看起来一点都不正确 public class PlayerController :
public class PlayerController : MonoBehaviour
{
public float speed = 3.0f;
public float jumpForce = 4.0f;
public Rigidbody2D rb;
public Vector2 movement;
public bool isJumping;
public Animator animate;
public Vector2 jumping = new Vector2(0,1);
// Start is called before the first frame update
void Start()
{
rb = this.GetComponent<Rigidbody2D>();
//animate = this.GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
//animate.SetFloat("Horizontal", Input.GetAxis("Horizontal"));
movement = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
}
void FixedUpdate()
{
moveCharacter(movement);
jumpCharacter();
}
void moveCharacter(Vector2 direction)
{
rb.velocity = direction * speed;
}
void jumpCharacter()
{
if(Input.GetKey(KeyCode.Space) && !isJumping)
{
isJumping = true;
rb.AddForce(jumping * jumpForce);
}
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
isJumping = false;
rb.velocity = Vector2.zero;
}
}
}
公共类PlayerController:MonoBehavior
{
公共浮子速度=3.0f;
公共浮子跳线力=4.0f;
公共刚体2d rb;
公共矢量运动;
公共场所在跳跃;
公共动画师;
公共向量2跳跃=新向量2(0,1);
//在第一帧更新之前调用Start
void Start()
{
rb=this.GetComponent();
//animate=this.GetComponent();
}
//每帧调用一次更新
无效更新()
{
//animate.SetFloat(“水平”,Input.GetAxis(“水平”);
移动=新矢量2(Input.GetAxis(“水平”),Input.GetAxis(“垂直”);
}
void FixedUpdate()
{
移动字符(移动);
jumpCharacter();
}
无效移动字符(矢量2方向)
{
rb.速度=方向*速度;
}
void jumpCharacter()
{
if(Input.GetKey(KeyCode.Space)&&&!isJumping)
{
isJumping=true;
rb.附加力(跳跃*跳跃力);
}
}
空心OnCollisionInter2D(碰撞2D碰撞)
{
if(collision.gameObject.CompareTag(“地面”))
{
isJumping=false;
rb.速度=矢量2.0;
}
}
}
您有Input.GetKey(KeyCode.Space)
。将GetKey
更改为GetKeyDown
如果您正在查找
GetKey
,则在按住该键时,该变量将始终为trueGetKeyDown
确保每次按下键时代码都可以运行一次。像这样尝试rigidbody.AddForce(velocity,ForceMode.VelocityChange)
对不起,我不太清楚你的意思。我应该把用户定义的jumpForce变量放在哪里?而不是写rb.AddForce(jumping*jumpForce)代码>您将编写rb.AddForce(跳跃*jumpForce,ForceMode.VelocityChange)
这不起作用,但我已经在Reddit上与某人交谈过,他们提到了一些关于Update()和FixeUpdate()的事情,我甚至不太确定。如果其他建议都不起作用,那么这只意味着问题不在代码范围内,也许你的游戏对象没有刚体,或者它的参数不允许它随物理运动。所以试着调整它们,用刚体创建新的游戏对象,分配这个脚本并测试它。好的,我正在使用GetKeyDown
,但它实际上仍然不起作用。