Hello, im making a 2D shooter game were the gun rotates 360 around the player. But when i flip the character depending on the direction im walking the whole gun flips and inverts the controls. The gun aims at the mousepointer.
This is my gun rotate script. It sits on a gameObject behind the player that is a child of the player. The problem is that i flip the player and that flips all its children aswell.
Im wondering if there is anyway i can prevent it.
public class AimRotate : MonoBehaviour
{
[SerializeField]
public GameObject player;
void Start()
{
}
void Update()
{
Vector3 mousepos = Input.mousePosition;
Vector3 gunposition = Camera.main.WorldToScreenPoint(transform.position);
mousepos.x = mousepos.x - gunposition.x;
mousepos.y = mousepos.y - gunposition.y;
float gunangle = Mathf.Atan2(mousepos.y, mousepos.x) * Mathf.Rad2Deg;
if (Camera.main.ScreenToWorldPoint(Input.mousePosition).x < transform.position.x)
{
transform.rotation = Quaternion.Euler(new Vector3(180f, 0f, -gunangle));
}
else
{
transform.rotation = Quaternion.Euler(new Vector3(0f, 0f, gunangle));
}
}
}
This is the movement script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[SerializeField]
public float movementSpeed;
[SerializeField]
public float jumpForce;
[SerializeField]
public float sprintSpeed;
[SerializeField]
public float fallSpeed;
private Rigidbody2D _rigidbody;
private float timer;
public bool isGrounded = false;
private bool facingRight = true;
void Start()
{
_rigidbody = gameObject.GetComponent<Rigidbody2D>();
}
void Update()
{
Movement();
Jump();
Sprint();
}
public void Movement()
{
Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, 0f);
transform.position += movement * Time.deltaTime * movementSpeed;
if (facingRight == false && movement.x > 0)
{
Flip();
}
else if(facingRight == true && movement.x < 0)
{
Flip();
}
}
public void Jump()
{
if (Input.GetButtonDown("Jump") && isGrounded == true)
{
_rigidbody.AddForce(new Vector2(0f, jumpForce), ForceMode2D.Impulse);
}
if (_rigidbody.velocity.y < 0)
{
_rigidbody.velocity += Vector2.up * (Physics2D.gravity.y * (fallSpeed - 1) * Time.deltaTime);
}
}
public void Sprint()
{
if (Input.GetKey(KeyCode.LeftShift) && isGrounded == true)
{
if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D))
{
var sprint = Input.GetAxis("Horizontal");
transform.position += new Vector3(sprint, 0, 0) * (Time.deltaTime * sprintSpeed);
}
}
}
public void Flip()
{
facingRight = !facingRight;
Vector3 Scaler = transform.localScale;
Scaler.x *= -1;
transform.localScale = Scaler;
}
}