Unity-当我的弹丸击中我的球为什么会朝相反的方向滚动?

问题描述 投票:0回答:1

[出于某种奇怪的原因,每当我的刚体球从我身上滚开时,当我用刚体弹丸“射击”它时,球就会改变方向并朝着我移动,而不是远离我。否则,物理效果会很好(如果当用弹丸射击时球朝着玩家目标滚动,则弹丸的撞击会以正确的方向/物理方式弹回/敲打球。)

我的弹跳代码已附加,我用它从墙壁等弹跳球,并且运行良好。我猜想是因为当球撞击时,球总是朝墙壁移动。我为为什么当我射击球时球从我身上滚开而立即改变方向而感到困惑。我尝试了不同的质量,阻力,物理材料,重力-我想到的所有方法都无济于事。

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个回答
0
投票

问题是方法Vector3.Reflect()。如果您向后移动,它将输出向前的速度。方法Vector3.Reflect()用于对象从表面或弹跳弹起。

您要做的是使用Rigidbody.AddForce()

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

© www.soinside.com 2019 - 2024. All rights reserved.