I'm not a good programmer, for my bodypart-based collision detection in a game in unity I'm making I've ended up with a switch that looks like this despite my best attempts to simplify and shorten it:
public void GetCollision(Collision2D col) {
if (attackType == -1) {
if (col.gameObject.name == "Sword") {
hitboxDisable();
} else if (col.gameObject.name == "Player") {
pim.PlayerDamage(5);
}
}
if (col.gameObject.name == "Player_Body") {
switch (attackType) {
case -2: {
pim.PlayerDamage(5);
}
break;
case 0:
if (!pa.playerIsDodging) {
pim.PlayerDamage(5);
} else {
pa.dodgeOnCooldown = false;
pa.resetDodgeRoutine();
hitboxDisable();
}
break;
case 1:
if (!swordSrc.isDefendingLegRight) {
pim.PlayerDamage(5);
} else {
weaponBlocked = true;
}
break;
case 2:
if (!swordSrc.isDefendingArmRight) {
pim.PlayerDamage(5);
} else {
weaponBlocked = true;
}
break;
case 3:
if (!swordSrc.isDefendingHeadRight) {
pim.PlayerDamage(5);
} else {
weaponBlocked = true;
}
break;
case 4:
if (!swordSrc.isDefendingLegLeft) {
pim.PlayerDamage(5);
} else {
weaponBlocked = true;
}
break;
case 5:
if (!swordSrc.isDefendingArmLeft) {
pim.PlayerDamage(5);
} else {
weaponBlocked = true;
}
break;
case 6:
if (!swordSrc.isDefendingHeadLeft) {
pim.PlayerDamage(5);
} else {
weaponBlocked = true;
}
break;
}
if (weaponBlocked == true) {
hitboxDisable();
RandomOpening();
ApplyForce(testvar1, testvar2);
weaponBlocked = false;
}
}
}
How can this be shortened and optimized for better readability? I'm new to C# and what little of my programming has been in C, I know there are a lot of ways to improve readability in C# I just don't know when/how to apply them. Suggestions would be much appreciated, I'm willing to try and learn anything, I want to try and avoid ending up with big switch statements like this if possible. Even just a suggestion what to apply here would be really appreciated, an example would be great.
I made the attackTypes into integers, they could have been strings but I chose not to because to my understanding strings take longer to compare. The attackType value specifies in the switch where the attack is targeting and if/how to block it, then if it was blocked.
swordSrc.isDefendingArmLeft,swordSrc.isDefendingHeadLeft, etc. and greatly reduce the repeated code. If the attack type matches the defense type you block, otherwise you take damage.