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
  • \$\begingroup\$ Have you looked into physics layers? \$\endgroup\$ Commented Jan 13, 2024 at 20:23

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\$ Commented Jan 15, 2024 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\$ Commented Jan 16, 2024 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\$ Commented Jan 19, 2024 at 12:24
  • \$\begingroup\$ isFreediving would be even better than isSwimmingUnderWater, but nevermind. \$\endgroup\$ Commented Jan 19, 2024 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.