【发布时间】:2020-05-28 22:23:24
【问题描述】:
出于某种奇怪的原因,每当我的刚体球从我身边滚开,而我用刚体弹丸“射击”它时,球就会改变方向并朝我移动,而不是远离我。否则物理工作正常(如果球在用射弹射击时向玩家对象滚动,射弹的影响会以正确的方向/物理方式反弹/敲开球。)
附上了我的反弹代码,我用它来将球从墙壁/等处反弹,它运行良好。我想这是因为球在撞击它时总是朝着墙壁移动。我很困惑为什么当我射出球时它会立即改变方向。我尝试了不同的质量、阻力、物理材料、重力——我能想到的一切都无济于事。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BounceBall : MonoBehaviour
{
private Rigidbody rb;
public float bounceForce = 6f;
Vector3 lastVelocity;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void LateUpdate()
{
lastVelocity = rb.velocity;
}
private void OnCollisionEnter(Collision collision)
{
GameObject hitObject = collision.gameObject;
if (hitObject.tag == "Pusher")
{
float speed = lastVelocity.magnitude;
Vector3 direction = Vector3.Reflect(lastVelocity.normalized, collision.contacts[0].normal);
rb.velocity = direction * Mathf.Max(speed, bounceForce * 3.5f);
}
else if (hitObject.tag == "Untagged")
{
float speed = lastVelocity.magnitude;
Vector3 direction = Vector3.Reflect(lastVelocity.normalized, collision.contacts[0].normal);
rb.velocity = direction * Mathf.Max(speed, bounceForce);
}
}
}
还有弹丸代码(别以为跟这个有什么关系)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Projectile : MonoBehaviour
{
public GameObject projectile;
[SerializeField] float projVel = 50f;
[SerializeField] float projLifeTime = 3.5f;
[SerializeField] float projTimer;
private Rigidbody rb;
void Start()
{
rb = projectile.GetComponent<Rigidbody>();
projTimer = projLifeTime;
//rb.AddForce(0,projVel,0, ForceMode.Impulse);
rb.AddForce(transform.forward * projVel, ForceMode.Impulse);
}
private void Update()
{
projTimer -= Time.deltaTime;
if(projTimer <= 0f)
{
Destroy(gameObject);
}
}
【问题讨论】: