问题描述
第一:对不起我的英语!!!
大家好,我是 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。