- Home /
Problem with gun rotation after flipping character (2D)
Guys I have the following problem. It's 2D platformer. I have a character with gun attached to it, and on gun I have script for rotating itself based on cursor position. I normally start game right sided and I want to make it so if the player rotates gun (with mouse) more than 85 degrees lets say, it should be flipped over and gun should be positioned at 180' - angle. It works, but I have another problem..
I want to do it both ways (ie when right sided and rotates gun upwards or downwards really hard, flip it, and also if it's left sided and rotates gun upwards or downwards really hard, flip it again). The problem is once I'm flipped, degrees are messed up and simply expression (angle>90) won't cut it, because if I only slightly rotate gun downwards, it's already 300 and it snaps even it that position..
Here are a few images to help:
The code is:
if (GameControl.control.isFacingRight == true)
{
Vector3 pos = Camera.main.WorldToScreenPoint(transform.position);
Vector3 dir = Input.mousePosition - pos;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
if (angle > 90 && !wasFlipped)
{
transform.parent.gameObject.GetComponent<PlayerControllerScript>().Flip();
wasFlipped = true;
}
}
else if (GameControl.control.isFacingRight == false)
{
Vector3 pos = Camera.main.WorldToScreenPoint(transform.position);
Vector3 dir = Input.mousePosition - pos;
float angle = 180f - (Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg);
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
if (angle > 90 && wasFlipped)
{
transform.parent.gameObject.GetComponent<PlayerControllerScript>().Flip();
wasFlipped = false;
}
}
The problem, once again is, in the latter block, if I'm facing left I can't just ask if angle > 90, because if I move aim a tiny bit below horizontal axis I end up with 360 degrees and because it's bigger than 90 I automatically get flipped at waist level..
It's really hard for me to explain it like this, but I hope you guys understand my problem :/
Thanks!
Answer by SuperTasche · Jun 28, 2017 at 12:18 AM
Hello.
It's been a while and you probably already found the answer yourself. However I will give a code snippet in order to explain how I solved this issue, since I am implementing the same mechanics:
if (rotationZ <= 90) {
transform.rotation = Quaternion.Euler(0f, 0f, rotationZ);
} else if (rotationZ >= 270) {
transform.rotation = Quaternion.Euler(0f, 0f, rotationZ);
}
if (rotationZ > 90 && rotationZ < 270) {
FlipPlayer();
}
Your answer
Follow this Question
Related Questions
I need help with aiming a ball. 2 Answers
Looking and firing towards mouse position, 2d game. 3 Answers
AI reflect shooting 0 Answers
Use the mouse to aim? 2 Answers
2D Aiming and Shooting at the mouse 3 Answers