在Unity中将弹丸反射到碰撞

Question3r

当射击弹丸时,我执行

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看来我必须旋转弹丸才能改变其运动方向。

伯恩哈德

为了反映弹丸,请控制刚体的速度。在这个例子中,我使用一个立方体(上面有这个脚本)作为弹丸,并用一些立方体包围它。

没有对撞机标记为触发器。这是它的外观: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;
  }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章