英文:
Why is my player movement inverted when I turn around?
问题
我经常使用刚体(rigidbodies),最近开始使用角色控制器(character controllers)。我为我的角色控制器编写了基本的移动代码,如下所示:
public void Update()
{
isGrounded = controller.isGrounded;
if (isGrounded)
{
x = Input.GetAxis("Horizontal");
z = Input.GetAxis("Vertical");
}
Vector3 move = Vector3.forward * z + Vector3.right * x;
controller.Move(move * speed * Time.deltaTime);
if (Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
if (!isGrounded)
{
}
velocity.y += gravity * Time.deltaTime; // 跳跃时的重力
controller.Move(velocity * Time.deltaTime);
}
我使用这段代码的原因是,我试图确保当我的玩家跳跃时,跳跃 不会 跟随我的摄像机移动。这段代码实现了这一点,但是如果我在y轴上旋转180度,我的WASD键都会反转。我尝试添加 * (1) 但那只会使情况变得更糟。如果我将Vector3.forward 和 Vector3.right 替换为 transform.forward 和 transform.right,键盘就不再反转,但我的跳跃会受到鼠标移动的控制,所以我真的想让第一行代码正常工作。
英文:
I used rigidbodies a lot and recently started using character controllers. I have basic movement code for my character controller here:
public void Update()
{
isGrounded = controller.isGrounded;
if (isGrounded)
{
x = Input.GetAxis("Horizontal");
z = Input.GetAxis("Vertical");
}
Vector3 move = Vector3.forward * z + Vector3.right * x;
controller.Move(move * speed * Time.deltaTime);
if (Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
if (!isGrounded)
{
}
velocity.y += gravity * Time.deltaTime; // Gravity for jumps
controller.Move(velocity * Time.deltaTime);
}
The reason I am using this code is because I'm trying to make sure that when my player jumps, the jump does not follow my camera around. This code does that, however if I rotate 180 degrees on the y axis, my WASD keys all become inverted. I've tried adding * (1) but that just makes it worse. If I replace Vector3.forward & Vector3.right to transform.forward & transform.right, the keys are no longer inverted but then my jump is controlled by my mouse movement, so I'm really trying to get the first line of code to work.
答案1
得分: 2
Vector3.forward
始终是(1,0,0)。如果您希望移动基于摄像机的旋转,您需要使用Transform.forward
和Transform.right
(假设您的角色仅围绕y轴旋转)。
如果您不希望跳跃在空中可以控制,您需要编写逻辑来创建动量,并防止玩家在空中改变他们的动量。第一行永远不会起作用。
英文:
Vector3.forward
is always (1, 0, 0). If you want the movement to be based on the camera's rotation you need to use Transform.forward
and Transform.right
(Assuming your character only has rotation around the y axis)
If you don't want the jump to be controllable mid-air, you have to logic to create momentum and prevent the player from changing their momentum if they are in the air. The first line is never going to work.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论