c# - 在空中跳跃时如何保持动力?
问题描述
我有一些处理跳跃和移动的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FPSMovement : MonoBehaviour
{
[SerializeField] float jumpForce;
[SerializeField] Transform groundChecker;
[SerializeField] float checkRadius;
[SerializeField] LayerMask groundLayer;
[SerializeField] float speed;
[SerializeField] float resistance;
[SerializeField] float sprintMultiplier = 1.5f;
Rigidbody rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void FixedUpdate()
{
bool IsOnGround() {
Collider[] colliders = Physics.OverlapSphere(groundChecker.position, checkRadius, groundLayer);
if (colliders.Length > 0) {
return true;
}else {
return false;
}
}
float x = Input.GetAxisRaw("Horizontal");
float z = Input.GetAxisRaw("Vertical");
Vector3 moveBy = transform.right * x + transform.forward * z;
float actualSpeed = speed;
if (Input.GetKeyDown(KeyCode.Space) && IsOnGround()) {
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
if (Input.GetKey(KeyCode.LeftShift)) {
actualSpeed *= sprintMultiplier;
}
if (IsOnGround() == false){
rb.MovePosition(transform.position + moveBy.normalized * actualSpeed * Time.deltaTime / resistance);
}
if (IsOnGround() == true){
rb.MovePosition(transform.position + moveBy.normalized * actualSpeed * Time.deltaTime);
}
}
}
但是当你跳跃并且你的机智会减慢你的速度。我怎样才能做到这一点,所以当你按下 w 时你只会慢慢地加速而不是失去速度。将底部的代码涂白,它在空中的速度不同,它在空中的速度与在地面上的速度相同,这是不现实的。
解决方案
原始代码不支持我正在尝试执行的操作,即如果您停止按下移动键,它将停止播放器。这意味着我试图通过提供的代码来保持势头是不可能的。例子:
float x = Input.GetAxisRaw("Horizontal");
float z = Input.GetAxisRaw("Vertical");
如果你不按任何东西,这些值将为 0,所以......
rb.MovePosition(transform.position + moveBy.normalized * actualSpeed * Time.deltaTime / resistance);
由于 moveBy 值为 0,玩家将停止,因为 0 * 任何数字都是 0。
如果您希望运动与我尝试做的相同,我会推荐 Dani 的教程: https ://www.youtube.com/watch?v=XAC8U9-dTZU
推荐阅读
- android - 在android studio中显示和隐藏栏的稳定视图
- python - 'str' 对象不能解释为文本抓取方法中的整数错误
- reactjs - 如何在 React 项目中集成 chrome 铸造
- c# - 有没有办法忽略asp.net核心中的特定属性包含多对多关系的函数
- ubuntu - 配置:错误:远程访问需要 curl。安装 curl 或使用 --disable-dap 构建
- mysql - Laravel InsertOrIgnore - 插入了哪些记录?
- python - discord.py 等待 channel.connect 超时
- ionic-framework - 离子原生闪屏 vs 电容闪屏?
- python - 如何显示通过 aiortc 接收的流而不写入文件
- python - 如何在带有美丽汤的类中找到标签