[英]Why does my Button not work with methods inside a class in Unity?
[英]Unity - Why does this only work inside the if statement
我在移动角色时遇到问题。
以下代码有效。
if (controller.isGrounded)
{
// X/Z Movement
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
// Y Movement.
if (Input.GetButtonDown("Jump"))
moveDirection.y = jumpForce;
}
// Apply gravity.
moveDirection.y -= grav * Time.deltaTime;
// Move the player.
print(moveDirection);
controller.Move(moveDirection * Time.deltaTime);
但是,如果我在if语句之前在X / Z Movement和Y Movement注释之间移动所有内容,则播放器只会掉落少量,而不会随着播放时间的延长而增加。 有人知道发生了什么吗?
哎呀。 这是因为Im会在Update的每个循环中重置moveDirection.y,因此与其叠加重力,不如将其重置为0,然后应用-= grav * Time.deltatime
几周前,我曾遇到过同样的问题,我想我可以帮忙:您看到的实际“问题”来自这里:
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
如果播放器接地,则没有理由在Y轴上移动他,因此其值为0,但是如果将其移动到Update之外,它将继续重置每一帧。
现在这行: moveDirection.y -= grav * Time.deltaTime;
从Vector3的Y减去0,而不是从moveDirection创建的moveVector的Y moveDirection.y = jumpForce;
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.