【问题标题】:Player movement script like in FPS, Unity3dFPS、Unity3d 中的玩家移动脚本
【发布时间】:2020-04-02 19:58:27
【问题描述】:

我有 2 个脚本,可以让玩家像在 FPS 游戏中一样移动。但它不会移动到玩家正在看的那个方向 - 它总是移动到同一个方向,无论相机的方向如何..

mouselook.cs

float yRotation;
float xRotation;
float lookSensitivity = 5;
float currentXRotation;
float currentYRotation;
float yRotationV;
float xRotationV;
float lookSmoothnes = 0.1f; 

void Update ()
{
    yRotation += Input.GetAxis("Mouse X") * lookSensitivity;
    xRotation -= Input.GetAxis("Mouse Y") * lookSensitivity;
    xRotation = Mathf.Clamp(xRotation, -80, 100);
    currentXRotation = Mathf.SmoothDamp(currentXRotation, xRotation, ref xRotationV, lookSmoothnes);
    currentYRotation = Mathf.SmoothDamp(currentYRotation, yRotation, ref yRotationV, lookSmoothnes);
    transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
}

playermovement.cs

public float walkSpeed = 6.0F;
public float jumpSpeed = 8.0F;
public float runSpeed = 8.0F;
public float gravity = 20.0F;

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

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

void Update()
{
    if (controller.isGrounded)
    {
        moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
        moveDirection = transform.TransformDirection(moveDirection);
        moveDirection *= walkSpeed;
        if (Input.GetButton("Jump"))
            moveDirection.y = jumpSpeed;
    }
    moveDirection.y -= gravity * Time.deltaTime;
    controller.Move(moveDirection * Time.deltaTime);
}

【问题讨论】:

  • 您是否尝试过对 playermovement.cs 使用 lateUpdate()
  • @BurakKarasoy 现在我尝试使用它来代替Update,但它没有帮助
  • 我会尝试在 playermovement.cs 函数中创建一个函数,并在此处更新所有代码,然后在 mouselook.cs 的更新函数的末尾调用此函数以了解这两个脚本的同步之间是否存在问题。
  • 您的两个脚本是否都附加到角色 GameObject 上?我尝试重现您的问题,但效果很好。
  • @ziwert 是问题所在,谢谢

标签: c# unity3d


【解决方案1】:

让你的鼠标看起来像这样

float lookSensitivity = 5;
float mouseX,mouseY;
public Transform playerBody;
float xRotation = 0f;

void Update ()
{
    float mouseX = Input.GetAxis("Mouse X") * mouseSentivity * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSentivity * Time.deltaTime;

        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);
        transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);

        playerBody.Rotate(Vector3.up * mouseX);

}

保存并将您的播放器从层次结构拖动到相机脚本 playerBody。

【讨论】:

    【解决方案2】:

    它不需要像 requirecomponentTypeof 或类似的东西吗

    【讨论】:

    • 请更清楚你的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多