c# - 当角色环顾四周时,Contoller 脚本不会改变方向
问题描述
我正在使用 Unity 官方网站上的控制器脚本来移动我的角色。我还使用脚本来使用鼠标转动相机。一切正常,直到角色环顾四周并面向不同的方向。然后 WASD 控件根据原始方向移动它们。例如,如果我转动 180 度,W 将我向后移动,S 将我向前移动。
我试图用 transform.forward 来解决这个问题,但我真的不知道我在做什么。
运动脚本:
CharacterController characterController;
public float speed = 6.0f;
public float jumpSpeed = 8.0f;
public float gravity = 20.0f;
private Vector3 moveDirection = Vector3.zero;
void Start()
{
characterController = GetComponent<CharacterController>();
}
void Update()
{
if (characterController.isGrounded)
{
// We are grounded, so recalculate
// move direction directly from axes
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0.0f, Input.GetAxis("Vertical"));
moveDirection *= speed;
if (Input.GetButton("Jump"))
{
moveDirection.y = jumpSpeed;
}
}
// Apply gravity. Gravity is multiplied by deltaTime twice (once here, and once below
// when the moveDirection is multiplied by deltaTime). This is because gravity should be applied
// as an acceleration (ms^-2)
moveDirection.y -= gravity * Time.deltaTime;
// Move the controller
characterController.Move(moveDirection * Time.deltaTime);
}
感谢您的任何帮助 :)
解决方案
您可以使用Transform.TransformDirection
将本地方向转换为世界方向。使用您要移动的本地方向调用它,它将返回您可以提供的相应世界方向CharacterController.Move
:
void Update()
{
if (characterController.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. Gravity is multiplied by deltaTime twice (once here, and once below
// when the moveDirection is multiplied by deltaTime). This is because gravity should be applied
// as an acceleration (ms^-2)
moveDirection.y -= gravity * Time.deltaTime;
// Move the controller
characterController.Move(worldMoveDirection * Time.deltaTime);
}
事实上,旧的文档就CharacterController.Move
使用了这种方法!
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); }
推荐阅读
- mysql - 你能在 mysql 上使用 Okta 吗?
- python - validate_on_submit 验证用户输入的数据没有看到正确的表单值
- python - 我如何用 python 解决我的 virtualenv 问题?
- xcode - 如何在 Xcode 中使用 AppleScript 创建一个简单的 kext 安装程序?
- java - 如何检查 NumberFormatException:空字符串
- android - 使用片段和底部导航栏
- xml - 替换 XML 文档中的属性值
- r - r中的条件apply()
- reactjs - 基本示例反应弹簧
- airflow - 如何加快新 dag 在 Apache Airflow 中显示到 Web GUI 的过程?