【问题标题】:Reflect a projectile on collision in Unity在 Unity 中在碰撞时反射射弹
【发布时间】:2018-04-12 23:31:29
【问题描述】:

当发射弹丸时,我执行

private Rigidbody rigid;    

private Vector3 currentMovementDirection;

private void FixedUpdate()
{
    rigid.velocity = currentMovementDirection;
}

public void InitProjectile(Vector3 startPosition, Quaternion startRotation)
{
    transform.position = startPosition;
    transform.rotation = startRotation;
    currentMovementDirection = transform.forward;
}

我使用InitProjectile 作为我的Start 方法,因为我不销毁对象,我回收它并禁用渲染器。

当用射弹击中物体时,该射弹应该被反射。

我拍摄了一堵墙,这些墙多次反射物体

我认为 Unity 提供了一些东西

https://docs.unity3d.com/ScriptReference/Vector3.Reflect.html

碰撞触发时

private void OnTriggerEnter(Collider other)
{
    if (other.gameObject == projectile)
    {
        projectileComponent.ReflectProjectile(); // reflect it
    }
}

我想通过使用来反映它

public void ReflectProjectile()
{
    // Vector3.Reflect(... , ...);
}

但是我必须使用什么作为 Reflect 的参数?看来我必须旋转弹丸才能改变它的运动方向。

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    为了反射弹丸操纵刚体的速度。在这个例子中,我使用一个立方体(上面有这个脚本)作为射弹和一些围绕它的立方体。

    没有碰撞器被标记为触发器。这是它的外观:https://youtu.be/2Lfj-li6x8M

    public class testvelocity : MonoBehaviour
    {
      private Rigidbody _rb;
      private Vector3 _velocity;
    
      // Use this for initialization
      void Start()
      {
        _rb = this.GetComponent<Rigidbody>();
    
        _velocity = new Vector3(3f, 4f, 0f);
        _rb.AddForce(_velocity, ForceMode.VelocityChange);
      }
    
      void OnCollisionEnter(Collision collision){
        ReflectProjectile(_rb, collision.contacts[0].normal);
      }
    
      private void ReflectProjectile(Rigidbody rb, Vector3 reflectVector)
      {    
            _velocity = Vector3.Reflect(_velocity, reflectVector);
        _rb.velocity = _velocity;
      }
    }
    

    【讨论】:

    • 当给定参数乘以速度时,没有任何变化。当将整个速度乘以 -1 时,整个方向都会改变..
    • 好的,修复了使用反射的代码。代码现在基于控制弹丸。
    【解决方案2】:

    我尝试了另一种使用 Raycast 的方法

    public void ReflectProjectile()
    {
        RaycastHit hit;
        Ray ray = new Ray(transform.position, currentMovementDirection);
    
        if (Physics.Raycast(ray, out hit))
        {
            currentMovementDirection = Vector3.Reflect(currentMovementDirection, hit.normal);
        }
    }
    

    这对我来说很好用

    【讨论】:

      猜你喜欢
      • 2013-11-16
      • 1970-01-01
      • 1970-01-01
      • 2022-06-29
      • 1970-01-01
      • 1970-01-01
      • 2012-10-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多