unity3d 跳转时,旋转值变为0

hgncfbus  于 2023-01-05  发布在  其他
关注(0)|答案(1)|浏览(179)

这是我的运动剧本。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public CharacterController controller;

    public float turnSmoothTime = 0.1f;
    float turnSmoothVelocity;
    public float Speed = 10f;

    private Vector3 moveDirection;

    public float groundDistance = 0.4f;
    public float gravity = -9.81f;
    public float jumpPower = 3.5f;
    public float directionY;
    bool isGrounded;

    public Animator anim;

    public Transform cam;

    private void Update()
    {
        float horizontal = Input.GetAxisRaw("Horizontal");
        float vertical = Input.GetAxisRaw("Vertical");

        moveDirection = new Vector3(horizontal, 0f, vertical).normalized;
        if (controller.isGrounded)
        {
            if (Input.GetKeyDown(KeyCode.Space))
            {
                directionY = jumpPower;
            }
            else
            {
                directionY = 0;
            }
        }
        if (!controller.isGrounded)
        {
            directionY += gravity * Time.deltaTime;
        }
        moveDirection.y = directionY;

        if (moveDirection.magnitude >= 0.1f)
        {
            float targetAngle = Mathf.Atan2(moveDirection.x, moveDirection.z) * Mathf.Rad2Deg;
            float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);

            transform.rotation = Quaternion.Euler(0f, angle, 0f);

            controller.Move(moveDirection * Speed * Time.deltaTime);
        }

        bool hasHorizontalInput = !Mathf.Approximately(horizontal, 0f);
        bool hasVerticalInput = !Mathf.Approximately(vertical, 0f);
        bool isWalking = hasHorizontalInput || hasVerticalInput;

        

    }

}

我想用characterController做一个平滑的跳跃系统。我的代码在基础状态下工作正常,但是当我按空格键(跳跃)时,它会将当前的旋转y值返回到0。(我想这个问题是因为跳跃的位置值是y,但是移动的旋转值也是y。)我怎么解决这个问题呢?我想即使我跳跃旋转值也不会改变。

t2a7ltrp

t2a7ltrp1#

我解决了。是代码执行顺序问题。

float horizontal = Input.GetAxisRaw("Horizontal");
    float vertical = Input.GetAxisRaw("Vertical");
    Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;

    if (controller.isGrounded && Input.GetButton("Jump"))
    {
        movingDirection.y = jumpSpeed;
    }

    movingDirection.y -= gravity * Time.deltaTime;
    controller.Move(movingDirection * Time.deltaTime * speed);

    if (direction.magnitude >= 0.1f)
    {
        float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg;
        float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
        transform.rotation = Quaternion.Euler(0f, angle, 0f);
        controller.Move(direction * speed * Time.deltaTime);
    }

相关问题