Reputation: 1
I am making a 2d shooter but I have run into an issue. When my character flips its scale to -1 when going left the rotation of the weapon hold inverts away from the cursor. Here is the mouse follow code I have in case it is needed.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public float offset;
void Update()
{
Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotZ + offset);
}
Any help is use full.
Upvotes: 0
Views: 541
Reputation: 141
Add this to your code.
if (rotZ < -90f || rotZ > 90f)
{
if (playerGameObject.transform.eulerAngles.y == 0f)
{
transform.localRotation = Quaternion.Euler (180f, 0f, rotZ);
}
else if (playerGameObject.transform.eulerAngles.y == 180f)
{
transform.localRotation = Quaternion.Euler (180f, 180f, -rotZ);
}
}
The full thing would be like this
public float offset;
void Update()
{
Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotZ + offset);
if (rotZ < -90f || rotZ > 90f)
{
if (playerGameObject.transform.eulerAngles.y == 0f)
{
transform.localRotation = Quaternion.Euler (180f, 0f, rotZ);
}
else if (playerGameObject.transform.eulerAngles.y == 180f)
{
transform.localRotation = Quaternion.Euler (180f, 180f, -rotZ);
}
}
}
This code changes the way you are rotating the gun if the player is flipped.
Upvotes: 0
Reputation: 20259
Use Mathf.Sign
to take the sign of the x scale into account when calculating the rotation. You will use it to negate x component of the rotation and the angle of rotation itself when the scale is flipped:
Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition)
- transform.position;
float scaleSign = Mathf.Sign(transform.localScale.x);
float rotZ = Mathf.Atan2(difference.y, difference.x * scaleSign) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, (rotZ + offset) * scaleSign );
Upvotes: 1