Hello,
I am trying to have the color of a ball change when it hits a wall in my game. The if statement I have for this works but when I try to have it change to a different color after it hits the right wall again this is where I have run into issues. When the code runs right now, anytime the ball contacts another surface including the paddles it changes color. So how should I proceed forward? Should I move the color-changing part of the code to its own method or is there a way to help it run independently from the other collision parts of the code in the method?
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.name == "RacketLeft")
{
float y = hitFactor(transform.position, collision.transform.position, collision.collider.bounds.size.y);
Vector2 dir = new Vector2(1, y).normalized;
GetComponent<Rigidbody2D>().velocity = dir * speed;
}
if (collision.gameObject.name == "RacketRight")
{
float y = hitFactor(transform.position, collision.transform.position, collision.collider.bounds.size.y);
Vector2 dir = new Vector2(1, y).normalized;
GetComponent<Rigidbody2D>().velocity = dir * speed;
}
if (collision.gameObject.name == "Right Wall")
{
_renderer.sharedMaterial = materials[1];
}
else
{
_renderer.sharedMaterial = materials[0];
}
}