c# - 刚体操作在 Y 轴上不起作用?(Unity3D 2020.1)
问题描述
这很奇怪。
我一直在更深入地了解刚体,我不能为了我的生命,让它跳跃。我正在完全复制我在 youtube 教程上看到的内容,它适用于 youtuber,但不适用于我。
在更多的 C# 英语中 - 我试图通过用户输入在 y 轴上添加 .AddForce(ForceMode.TriedEverything)。它不会始终如一地工作。有时它更高,有时更低,大多数时候什么都没有。这很奇怪。我什至没有设置 isGrounded 或任何其他限制。只需“如果用户输入,则添加强制”。这是案例 1
情况 2 简单得多,并且从不工作:它基于将速度设置为仅操纵 y 轴的新向量。我会分享代码。“jumpForce”设置为 12,但我也试过 500。没有不同。这个案例确实有一个“接地”的条件,但没有它也无法工作。无论如何,两个打印语句都会被执行。
两种情况都在 Update 和 FixedUpdate 中进行了测试,没有差异。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMotor : MonoBehaviour
{
public LayerMask layerMask = default;
public bool grounded;
[SerializeField] float moveSpeed = 7f;
[SerializeField] float jumpForce = 12f;
Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
float x = Input.GetAxisRaw("Horizontal") * moveSpeed;
float y = Input.GetAxisRaw("Vertical") * moveSpeed;
Vector3 movePosition = transform.right * x + transform.forward * y;
Vector3 newPosition = new Vector3(movePosition.x, rb.velocity.y, movePosition.z);
grounded = Physics.CheckSphere(new Vector3(transform.position.x, transform.position.y - 1, transform.position.z), 0.4f, layerMask);
if (Input.GetKeyDown(KeyCode.Space)&& grounded)
{
print("reached if statement");
rb.velocity = new Vector3(rb.velocity.x, jumpForce, rb.velocity.z);
print("jumpingjumping");
}
rb.velocity = newPosition;
}
void FixedUpdate()
{
}
}
谢谢各位。
解决方案
问题是您的代码的顺序。您在 jump 语句之前设置 newPosition 变量,因此 y 速度为 0,然后您将 y 速度设置为 jump 速度,但之后您将速度设置为 newPosition,它的速度仍然为 0,因为它是之前设置的跳转语句。这是工作代码:
public LayerMask layerMask = default;
public bool grounded;
[SerializeField] float moveSpeed = 7f;
[SerializeField] float jumpForce = 12f;
Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
float x = Input.GetAxisRaw("Horizontal") * moveSpeed;
float y = Input.GetAxisRaw("Vertical") * moveSpeed;
Vector3 movePosition = transform.right * x + transform.forward * y;
grounded = Physics.CheckSphere(new Vector3(transform.position.x, transform.position.y - 1, transform.position.z), 0.4f, layerMask);
if (Input.GetKeyDown(KeyCode.Space) && grounded)
{
print("reached if statement");
rb.velocity = new Vector3(rb.velocity.x, jumpForce, rb.velocity.z);
print("jumpingjumping");
}
Vector3 newPosition = new Vector3(movePosition.x, rb.velocity.y, movePosition.z);
rb.velocity = newPosition;
}
void FixedUpdate()
{
}
希望这对您有所帮助!
推荐阅读
- java - 我如何在主要活动中使用结果
- r - if 参数中的“参数长度为零”错误 - 比较向量中的两个值
- google-maps - 谷歌地图距离矩阵单位未正确显示
- c# - System.FormatException: '反序列化属性时发生错误。在 mongoDB.Driver C# 的帮助下使用聚合函数
- sql - 使用生成的系列填充列
- python - 涉及 Enum 的多重继承元类冲突
- heroku-postgres - 连接尝试失败。尝试连接到 Heroku PostgreSQL 时
- amazon-web-services - 在 AWS 上部署 Airflow 的最佳解决方案是什么?
- kotlin - 序列化地图
> - vue.js - 使用 v-if 语句后没有出现 Div