在函数内部,我必须在开始时声明两个局部浮点变量:jAxis
和jumpValue
。 jAxis
刚开始就被分配了一个变量,而jumpValue
只是float jumpValue;
我稍后在代码中有一个if
语句,其中使用了jumpValue
。但是,在达到这一点之前,切勿为jumpValue
分配一个值。编译器不同意在底部附近进行use of unassigned local variable jumpValue
计算时会显示错误Vector3
的错误。
这是我的相关代码:
void JumpHandler()
{
float jAxis = Input.GetAxis("Jump");
float jumpValue;
//if pressed
if (jAxis > 0)
{
bool isGrounded = CheckGrounded();
if (isGrounded)
{
jumpValue = jAxis;
if (!jumpPressed)
{
jumpPressed = true; //Pressed jump
}
}
else
{
jumpValue = 0;
}
}
else if (jumpPressed)
{
rb.AddForce(new Vector3(0, Math.Abs(jumpValue) * jumpForce * 1, 0) , ForceMode.VelocityChange);//Absolute value to prevent weird cases of negative jAxis
//jump key not pressed
jumpPressed = false;
jumpValue = 0;
}
else
{
jumpPressed = false;
}
}
答案 0 :(得分:0)
将if(jumpPressed)
块与if (jAxis > 0)
块排除是没有意义的。在else
之前删除if (jumpPressed)
。
此外,您应该将jumpValue
初始化为0f
,因为编译器无法单独认识到jumpPressed
仅在设置了jumpValue
时才为真。
您不需要else块将jumpPressed
设置为false,因为如果在该块中,则已经为false。
总的来说,看起来像这样:
void JumpHandler()
{
float jAxis = Input.GetAxis("Jump");
float jumpValue = 0f;
//if pressed
if (jAxis > 0)
{
bool isGrounded = CheckGrounded();
if (isGrounded)
{
jumpValue = jAxis;
if (!jumpPressed)
{
jumpPressed = true; //Pressed jump
}
}
else
{
jumpValue = 0;
}
}
if (jumpPressed)
{
rb.AddForce(
//Absolute value to prevent weird cases of negative jAxis
new Vector3(0, Mathf.Abs(jumpValue) * jumpForce, 0),
ForceMode.VelocityChange);
//jump key not pressed
jumpValue = 0;
jumpPressed = false;
}
}
这将产生如下输出(使用CheckGrounded
的伪方法返回一次true
):
答案 1 :(得分:0)
我看不到从何处调用JumpHandler
,但是使用bool
标志等进行的整个计算对我来说意义不大。
同时无需将该值存储在局部变量jumpValue
中。您只想在一个位置使用它,因此只需直接传递相应的值jAxis
。
由于您刚刚检查了jAxis > 0
,因此Mathf.Abs
是多余的。
您要将跳转的实际执行推迟到下一次在jumpHandler
时再次调用jAxis <= 0
时。如果不能满足条件,则直接执行跳转即可。不需要jumpPressed
标志。
因为只有在AddForce
作为强制倍增器传递给CheckGrounded
时,您才允许jAxis
也会导致意外的行为。这是一次调用,因为应该在下一帧(或无论在何处调用它)都不再接地。但是,jAxis
值可能很小(取决于您在那里使用的轴的类型)。
据我所知,您的代码与此大致相同(无需延迟跳转,只需传入jumpForce * 1
而不是jAxis
即可)
void JumpHandler()
{
float jAxis = Input.GetAxis("Jump");
if(jAxis > 0 && CheckGrounded)
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.VelocityChange);
}
}