【问题标题】:Unity - Why is my ball rolling in the opposite direction when a projectile hits it?Unity - 当弹丸击中它时,为什么我的球会朝相反的方向滚动?
【发布时间】: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);
        }
    }

【问题讨论】:

    标签: c# unity3d physics


    【解决方案1】:

    问题在于方法Vector3.Reflect()。如果你输入一个向后的速度,它将输出一个向前的速度。 Vector3.Reflect() 方法适用于从表面反弹的对象或弹跳。

    你想要做的是使用 Rigidbody.AddForce()

    这是文档:https://docs.unity3d.com/ScriptReference/Rigidbody.AddForce.html

    【讨论】:

    • 非常感谢。在更改并检查弹丸碰撞的标签后,我使用了 AddForceAtPosition。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-14
    • 2014-06-21
    • 1970-01-01
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多