2
\$\begingroup\$

Experimenting with my 1st Unity project. It's about a top down swimmer. By toggling the swimmer's collider, he can swim under boats:

if (Input.GetKeyDown(KeyCode.A)) swimmerCircleCollider.enabled = !swimmerCircleCollider.enabled;

At the same time I don't want him to be able to swim under the wharf, which is like an uncrossable barrier/border/wall or simply the end of playable area. How can I achieve that?

Is the idea of disabling the collider wrong in the first place? If so, please provide some guidelines for a better solution.

\$\endgroup\$
1

2 Answers 2

4
\$\begingroup\$
  • You can go to Edit->Project Setting->Physics or Physics 2D->Layer Collision Matrix. To change what you want your player pass through or not.
  • To change it via code like what you wanted, I have a solution here. Ex: your Player's Layer position is 6 & your Enemy is 7.

enter image description here

private bool isSwimmingUnderWater = false;
void Update()
{
    if (Input.GetKeyDown(KeyCode.A))
    {
        isSwimmingUnderWater = !isSwimmingUnderWater;
        Physics2D.IgnoreLayerCollision(6, 7, isSwimmingUnderWater); //it will set the val of the Layer Collision of the Player and Enemy whether true or false
    }
}

I have tested it with my game and it works.

\$\endgroup\$
4
  • \$\begingroup\$ The 'Order in Layer' under 'Sprite Renderer' is the order inside the assigned 'Builtin Layer' or 'User Layer'? \$\endgroup\$
    – Tomo
    Commented Jan 15 at 19:14
  • \$\begingroup\$ It's working. Please, change flag to a property like private bool isSwimmingUnderWater = false; and put the If statement inside the void Update() {} method, to make things clearer, so I can mark your answer as solved. Thank you. \$\endgroup\$
    – Tomo
    Commented Jan 16 at 20:47
  • \$\begingroup\$ Hey, I have changed my answer and sorry for my delayed response. Because of some problems with my laptop, now i having to code via my phone... \$\endgroup\$
    – Tien Hung
    Commented Jan 19 at 12:24
  • \$\begingroup\$ isFreediving would be even better than isSwimmingUnderWater, but nevermind. \$\endgroup\$
    – Tomo
    Commented Jan 19 at 15:15
1
\$\begingroup\$

To achieve a barrier you also could add a child object which gets activated and has an appropriate box collider.

But the Physics2D solution by Tien Hung is way more elegant!

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .