我有一个由刚体控制的玩家。Z轴上的移动在游戏中保持恒定,以使玩家向前移动。然而,这意味着刚体会不断加速,因此它在游戏开始时的速度比游戏结束时的速度慢得多。下面是我的脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;
public class Controller : MonoBehaviour
{
[Tooltip("Rigidbody component attached to the player")]
public Rigidbody rb;
public float forwardMax;
public float slowBy;
private float movementX;
private float movementY;
private float gravity = -9.81f;
private bool isJumping = false;
private bool isSlowing = false;
private bool isSpeeding = false;
private float speedX = 100;
private float speedY = 150000;
private float speedZ = 60;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
// if(!controller.isGrounded)
// {
// Vector3 gravityVector = new Vector3(0.0f, gravity, 0.0f);
// rb.AddForce(gravityVector * Time.deltaTime);
// }
}
void OnCollisionEnter(Collision collision)
{
// SceneManager.LoadScene(1);
}
// Update is called once per frame
void OnMove(InputValue movementValue)
{
Vector2 movementVector = movementValue.Get<Vector2>();
movementX = movementVector.x;
movementY = movementVector.y;
}
void OnJump()
{
isJumping = true;
}
void CalculateMovement()
{
if(rb.velocity.z > 20)
{
rb.drag = 20;
}
else
{
rb.drag = 0;
}
Vector3 movement = new Vector3(movementX * speedX, 0.0f, speedZ);
if(isJumping)
{
movement.y += Mathf.Sqrt(speedY * -3.0f * gravity);
isJumping = false;
}
rb.AddForce(movement);
Debug.Log("Speed is " + rb.velocity.z);
}
void FixedUpdate()
{
CalculateMovement();
}
}
有没有办法保持前进速度不变?当玩家跳跃时问题更严重。
首先,我试着钳制正向(z轴)矢量,但没有效果;然后,我试着在正向速度超过某个数值时,将反向矢量加到总和上,但这会导致它一直加速和减速;然后,我试着在rigidbody
上使用drag
,但效果相同。
2条答案
按热度按时间8zzbczxx1#
你可以使用刚体.速度,并将其设置为常量或任何你想要的值,而不是添加力。通过添加力,你的角色的速度增加。你也可以使用添加力,但你必须根据当前的速度动态调整力的值。
rigidbody velocity
ui7jx7zq2#
在FixedUpdate()的末尾直接设置您想要的z值怎么样?