2
votes

when shooting a projectile I execute

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;
}

I use InitProjectile as my Start method because I don't destroy the object, I recycle it and just disable the renderer.

When hitting a object with the projectile, this projectile should get reflected.

I shoot a wall and these walls reflect the objectile multiple times

Reflect

I think Unity provides something for this

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

When the collision is triggered

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

I want to reflect it by using

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

but what do I have to use as parameters for Reflect ? It seems I have to rotate the projectile that it changes its movement direction.

2

2 Answers

6
votes

To reflect the projectile manipulate the velocity of the rigidbody. In this example I use a cube(with this script on it) as the projectile and some cube ssurrounding it.

No collider is marked as trigger. Here is how it looks: 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
votes

I tried another way by using a 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);
    }
}

This works fine for me