gpt4 book ai didi

c# - 无法统一理解沿局部和全局空间的运动

转载 作者:行者123 更新时间:2023-11-30 22:52:17 25 4
gpt4 key购买 nike

CharacterController _charController;

// ...

moveInputX = Input.GetAxis("Horizontal") * speed;
moveInputZ = Input.GetAxis("Vertical") * speed;
Vector3 movement = new Vector3(moveInputX, 0, moveInputZ);
movement = Vector3.ClampMagnitude(movement, speed);

movement.y = -9.81f;

movement *= Time.deltaTime;
movement = transform.TransformDirection(movement);
_charController.Move(movement);

我有一个旋转的播放器,我想让他向他的本地方向移动,但我不明白何时从它移动的代码中删除 movement = transform.TransformDirection(movement);到全局方向,这没有任何意义,因为这行代码将方向从局部空间转换为全局空间。

最佳答案

这是因为 CharacterController.Move 需要世界空间中的向量。可悲的是,有关该文件的文档从未明确说明这一点。

当您在此处计算移动时:

Vector3 movement = new Vector3(moveInputX, 0, moveInputZ);

您可以看到它没有考虑角色变换的旋转。为了让它做到这一点,您需要找到这个向量在被解释为在角色的局部空间中时在世界空间中的样子。这正是这一行的作用:

movement = transform.TransformDirection(movement);

它将运动从局部空间转换到世界空间。

2018.1 CharacterController.Move documentation实际上在其示例中使用了 transform.TransformDirection:

using UnityEngine;
using System.Collections;

// The GameObject is made to bounce using the space key.
// Also the GameOject can be moved forward/backward and left/right.
// Add a Quad to the scene so this GameObject can collider with a floor.

public class ExampleScript : MonoBehaviour
{
public float speed = 6.0f;
public float jumpSpeed = 8.0f;
public float gravity = 20.0f;

private Vector3 moveDirection = Vector3.zero;
private CharacterController controller;

void Start()
{
controller = GetComponent<CharacterController>();

// let the gameObject fall down
gameObject.transform.position = new Vector3(0, 5, 0);
}

void Update()
{
if (controller.isGrounded)
{
// We are grounded, so recalculate
// move direction directly from axes

moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0.0f, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection = moveDirection * speed;

if (Input.GetButton("Jump"))
{
moveDirection.y = jumpSpeed;
}
}

// Apply gravity
moveDirection.y = moveDirection.y - (gravity * Time.deltaTime);

// Move the controller
controller.Move(moveDirection * Time.deltaTime);
}
}

关于c# - 无法统一理解沿局部和全局空间的运动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58272822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com