How to change the color of the ball after hitting square?

C# 2D

I have a multi colored square ( PIC I).

My BALL (PIC II) hits him.

How to change the color of the ball after hitting square?

The point is to make the ball change its color to the color it strikes.

E.g:

The ball hits the red part of square- ball turns red

The ball hits the green part of square - bal changes color to green

etc. etc.

I know I should use a collision, but I don’t know how.


Hi @polan31

All the answers above are pointing on the right direction. My suspect is that your colliders are not working properly.

Since you are playing in 2d, you must have a “Rigidbody 2D” on the circle object, and make sure it has “Circle Collider 2D” as well. As for the rectangles, make sure they have “Box Collider 2D”., the rectangles do not need to have rigidbody.

Good day.

You should first learn how to manage collisions/triggers. I recommend you to create 1 empty object for each color, with a collider in each object, to know what color has been touched.

Look at this tutorial.

Then, you have to change the material of the ball (you must have a material for each color), using Renderer.material.

We can help with some script problem or specific doubt, but you must learn how to use it by your own.

Bye!

Add a “Target” tag to each colored shaped that the ball can hit. Then add the following code into your ball script

private void OnCollisionEnter2D(Collision2D other)
{
    if (other.gameObject.tag == "Target")
    {
        GetComponent<SpriteRenderer>().color = other.gameObject.GetComponent<SpriteRenderer>().color;
    }
}

Try creating three empty game objects, only add Box Collider and Sprite Renderer components for them. These three is not necessary to be seen by player.

  1. adjust the scale of the box colliders.

The first collider is scaled and placed exactly as the size of the coloured square’s green color region,
the second collider matches the pink one and the third matches the red one.

  1. change the sprite renderer’s color as you wish.

Then, change the color in the sprite renderer of each collider object to the color of your coloured square respectively.

  1. adding conditions.

Then use the onCollisionEnter method mentioned above by sean to change the ball’s color.
If it hits the first collider, it changes to green, if it hits the second it changes to pink and if it hits the red one it changes to red.

i tried this and worked

	void OnCollisionEnter2D(Collision2D coll) 
	{
		if(coll.gameObject.tag=="Enemy")
		{
			Debug.Log ("Collision");


			Color one= coll.gameObject.GetComponent <SpriteRenderer>().color;

			gameObject.GetComponent <SpriteRenderer>().color=one;
		}
	}

here is demo

link text