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();
rb.AddForce(throwDirection * throwForce, ForceMode.Impulse);
}
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;
}
}