# Calculate new direction after collision

The ball comes straight to the box collider of the enemy and I would need it to bounce in one of the directions marked with red arrows with same velocity and I can’t figure out how to do it.

[SerializeField] private float throwForce = 10f;
[SerializeField] private float destroyTime = 1f;

Rigidbody rb;

bool destroy = false;

Vector3 throwDirection;

private void Awake()
{
rb = GetComponent<Rigidbody>();
}
private void Start()
{
throwDirection = GetComponentInParent<ThrowAction>().GetThrowDirection();
}
private void Update()
{
if (destroy)
{
destroyTime -= Time.deltaTime;
if(destroyTime <= 0)
{
Destroy(gameObject);
}
}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.transform.CompareTag("Enemy"))
{
Vector3 bounceOffset = new Vector3(4, 0, 4);

int randomIndex = Random.Range(0, 2);
switch (randomIndex)
{
case 0:
bounceOffset *= -1;
break;
case 1:

break;
}
Vector3 newDirection = (collision.transform.position - (collision.transform.position + bounceOffset)).normalized;
Vector3 currentVelocity = rb.velocity;

rb.velocity = Vector3.Reflect(newDirection, currentVelocity);
destroy = true;
}
}

You’re really overcomplicating things. If you know that it’s not like real life reflection, then you shouldn’t use Vector3.Reflect(). Here’s a simple example that shows the direction you want (-+45 degrees, you can add more options in array). You need to adapt it to set velocity to your rigidbody.

private float[] possibleDegreeOffsets = { 45.0f };

private void Awake() {
float randomAngle = possibleDegreeOffsets[Random.Range(0, possibleDegreeOffsets.Length)];
Vector3 newDirection = new Vector2(Mathf.Cos(randomAngle * Mathf.PI / 180), Mathf.Sin(randomAngle * Mathf.PI / 180));
if(Random.value > 0.5f) {
newDirection.x *= -1f;
}
Debug.Log(newDirection);
}

This is made for basic up/down direction. If you need it from any direction, then just rotate the result based on normal direction.