- Home /
Problem with 2D gun rotation script (Would really apreaciate help)
I'm gonna provide you with a Gif of the Problem. The problem seems to be that the Pivot of the gun is attached to the Player, and the flip in the CharacterController script seems to double flip the gun. But I honestly have no clue how to fix it. I'll provide you with the code aswell.
public float speed = 5f;
public Rigidbody2D rb;
bool facingRight = true;
Vector2 move;
public Animator animator;
void Update()
{
move.x = Input.GetAxisRaw("Horizontal");
move.y = Input.GetAxisRaw("Vertical");
animator.SetFloat("Speed", move.sqrMagnitude);
// using mousePosition and player's transform (on orthographic camera view)
var delta = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
if (delta.x >= 0 && !facingRight)
{ // mouse is on right side of player
transform.localScale = new Vector3(1, 1, 1); // or activate look right some other way
facingRight = true;
}
else if (delta.x < 0 && facingRight)
{ // mouse is on left side
transform.localScale = new Vector3(-1, 1, 1); // activate looking left
facingRight = false;
}
}
private void FixedUpdate()
{
rb.MovePosition(rb.position + move.normalized * speed * Time.fixedDeltaTime);
}
Thats the character Controller
public GameObject myPlayer;
private void FixedUpdate()
{
Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
difference.Normalize();
float rotationZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotationZ);
if (rotationZ< -90 || rotationZ> 90)
{
if(myPlayer.transform.eulerAngles.y == 0)
{
transform.localRotation = Quaternion.Euler(180, 0, -rotationZ);
} else if (myPlayer.transform.eulerAngles.y == 180) {
transform.localRotation = Quaternion.Euler(180, 180, -rotationZ);
}
}
}
And thats the gun pivot script, the gun sprite being attached to the pivot point which itself is attached to the Player object. I would be really thankful for some help. Thanks in advance.
Answer by ShadyProductions · Jun 11, 2020 at 08:07 PM
Why don't you just do the same with the gun like u did the player instead of messing with localrotation, just invert the localScale
transform.localScale = new Vector3(-1, 1, 1); // right
transform.localScale = new Vector3(1, 1, 1); // left
Hello, thank for the quick answer. Where would I put that code in?
I just tried to replace the localRotation with localScale but it didn't seem to fix the problem
Your answer
Follow this Question
Related Questions
How to keep Diagonal Movement Direction in 2D Isometric game? 0 Answers
help with freezing 2D sprite rotation 2 Answers
How to Change a sprite mesh at a certain frame in an animation clip without script? 1 Answer
How can I stop a glitch where my character transitions from left to right he snaps back? 0 Answers
Jump Animation 2D problems 0 Answers