- Home /
Swapping the Position of an element on certain conditions
Hi all,
STRUCTURE: Player -> Arm -> (Various Weapon Classes)
I have a Player, which has a Child object called Arm. Arm rotates to follow the mouse cursor, but I wanted to avoid the weird situation where a player could "point" their weapon directly behind their character, thus sticking through the player's body. To do this, I prevented the Arm from pointing such that the X position was less than 0. This worked OK, but now I want to "flip" the situation when the player is facing left (so that Arm cannot be higher than 0). This is simple enough, but the problem comes in here:
I need to actually flip the arm's position in space, such that it is facing left rather than right. I also want to flip it such that the Weapon sprite (which is a child of Arm) is mirrored.
The problem is that, whenever I actually do so, the weapon's position is erratic and not what would be expected, and that if you wiggle right and left enough, sometimes the weapon will "break", the Z rotation will bizarrely become something like 270 (even though no code ever sets it to anything other than 0), and the weapon will detach itself from the Player and float a substantial distance beneath his torso. This is rather disconcerting.
The code is:
void Flip ()
{
// Switch the way the player is labelled as facing.
//also need to check which direction we're facing before flipping. Then, if facing right, move Arm's Transform
Transform arm = transform.FindChild("Arm");
float armXPos = arm.transform.position.x;
float armYPos = arm.transform.position.y;
float armYRotLeftToRight = 0;
float armYRotRightToLeft = 180;
//If we're facing right when the flip is ordered
if (facingRight) {
arm.transform.position = new Vector3((armXPos),(0), 0);
arm.transform.rotation = Quaternion.Euler(0, armYRotRightToLeft, 0);
}
else {
arm.transform.position = new Vector3((armXPos * -1), 0, 0);
arm.transform.rotation = Quaternion.Euler(0, armYRotLeftToRight, 0);
}
facingRight = !facingRight;
// Multiply the player's x local scale by -1.
Vector3 theScale = playerGraphics.localScale;
theScale.x *= -1;
playerGraphics.localScale = theScale;
}
Does anyone have any ideas as to how I might flip the weapon properly with the user?
Thanks.
Your answer
Follow this Question
Related Questions
Flip over an object (smooth transition) 3 Answers
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
LookAt + Raycasting makes weapon rotate in a weird way 0 Answers