当我的 RigidBody 与 Collison 对象碰撞时,事件会被触发,但对象并不总是停止。这取决于它的速度,但这对我来说是不可接受的。我怀疑这与更新的工作方式有关,但我无法了解这一点。
这是代码
public class Mover : MonoBehaviour
{
private Rigidbody _rb;
private bool _isColliding;
[SerializeField] private float moveSpeed = 1f;
// Start is called before the first frame update
void Start()
{
_rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
MovePlayer();
}
void MovePlayer()
{
float xValue = Input.GetAxis("Horizontal") * moveSpeed;
float zValue = Input.GetAxis("Vertical") * moveSpeed;
Vector3 movement = new Vector3(xValue, 0f, zValue);
_rb.MovePosition(_rb.position + movement * Time.fixedDeltaTime);
}
private void OnCollisionEnter(Collision collision)
{
_isColliding = true;
_rb.velocity = Vector3.zero;
_rb.angularVelocity = Vector3.zero;
}
}
但是在调试 _rb.velocity 时 _rb.angularVelocity 似乎已经为零
我尝试的是
public class WallHit : MonoBehaviour
{
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Player"))
{
Rigidbody rbdy = collision.gameObject.GetComponent<Rigidbody>();
rbdy.velocity = Vector3.zero;
rbdy.angularVelocity = Vector3.zero;
}
}
}
void Update()
{
// Check for player input
if (!IsColliding())
{
MovePlayer();
}
}
bool IsColliding()
{
// Calculate movement vector based on player input
float xValue = Input.GetAxis("Horizontal") * moveSpeed;
float zValue = Input.GetAxis("Vertical") * moveSpeed;
Vector3 movement = new Vector3(xValue, 0f, zValue);
// Perform a collision check using a Raycast
RaycastHit hit;
if (Physics.Raycast(transform.position, movement, out hit, movement.magnitude * Time.deltaTime))
{
// If a collision is detected, return true
return true;
}
// If no collision is detected, return false
return false;
}
void MovePlayer()
{
// Move the player
float xValue = Input.GetAxis("Horizontal") * moveSpeed;
float zValue = Input.GetAxis("Vertical") * moveSpeed;
Vector3 movement = new Vector3(xValue, 0f, zValue);
_rb.MovePosition(_rb.position + movement * Time.fixedDeltaTime);
}
我已经没有主意了,我拒绝相信这无法处理
标准化运动向量:建议标准化运动向量,这样玩家在对角线移动时不会移动得更快。您可以通过在计算运动向量后调用 moving.Normalize() 来完成此操作。如果这不是解决方案,请告诉我有关场景的更多信息,以便我可以重新创建并解决问题。