微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

对角线运动比正常运动快

如何解决对角线运动比正常运动快

第一:对不起我的英语!!!

大家好,我是 Unity 的新手(5 天)。 今天我已经为刚体的基本动作制作了一个脚本,但是对角线动作比正常动作要快..我在互联网上搜索但我没有找到我能理解的帖子。

这里是我的脚本。 另外,如果你知道如何在我们跳跃时不移动,或者当我们向一个方向跳跃时,它会跟随这个方向,告诉我。 (我知道我的英语很糟糕。)另外,我是这个网站的新手。

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

public class PlayerMovements : MonoBehavIoUr
{
    
    [Serializefield] private float walkingSpeed;
    [Serializefield] private float runningSpeed;
    [Serializefield] private float jumpForce;
    [Serializefield] private float jumpRaycastdistance;
    
    private Rigidbody rb;
    float speed;
    Vector3 movement;
    
    /////////////////////////////////////////////////////
    
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }
    
    /////////////////////////////////////////////////////

    void Update()
    {
        Jumping();
    }
    
    /////////////////////////////////////////////////////
    
    private void FixedUpdate()
    {
        Movements();
    }
    
    /////////////////////////////////////////////////////
    
    private void Movements()
    {
        float hAxis = Input.GetAxisRaw("Horizontal");
        float vAxis = Input.GetAxisRaw("Vertical");
        
        if(Input.GetButton("Run"))
        {
            Vector3 movement = new Vector3(hAxis,vAxis) * runningSpeed *  Time.deltaTime;
            Vector3 newPosition = rb.position + rb.transform.TransformDirection(movement);
            rb.MovePosition(newPosition);
        }
        else
        {
            Vector3 movement = new Vector3(hAxis,vAxis) * walkingSpeed * Time.deltaTime;
            Vector3 newPosition = rb.position + rb.transform.TransformDirection(movement);
            rb.MovePosition(newPosition);
        }
    }
    
    /////////////////////////////////////////////////////
    
    private void Jumping()
    {
        if(Input.GetButtonDown("Jump"))
        {
            if (isGrounded())
            {
            rb.AddForce(0,jumpForce,ForceMode.Impulse);
            }
        }
    }
    
    /////////////////////////////////////////////////////
    
    private bool isGrounded()
    {
        return Physics.Raycast(transform.position,Vector3.down,jumpRaycastdistance);
    }
}

解决方法

你需要限制你的速度以保持它不变。查看Vector3.ClampMagnitude()

velocity = Vector3.ClampMagnitude(velocity,_movementSpeed);
            velocity.y = playerVelocity.Y; // keeping your Y velocity same since you have jumping.
            playerVelocity = velocity;

编辑:在您的情况下,它应该是这样的。 _maxSpeed 是速度限制。

private void FixedUpdate()
    {
        Movements();
        var clampedVelocity = Vector3.ClampMagnitude(rb.velocity,_maxSpeed);
        clampedVelocity.y = rb.velocity.y;
        rb.velocity = clampedVelocity;
    }
,

尝试标准化向量。 (更多信息在统一文档上,但 normalize() 将确保所有向量值的总和不大于 1。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。