Hello!
I’m currently having problems calculating the rotation offset for my 2D characters arms.
I’m really crappy at math and I can’t for my life figure out the correct method on how to get the right offset amount.
I managed to get the correct offset from -90 to 90 but not from -90 to 90 through 180.
I calculated the compensation angle by taking 90+25 degrees to get it to align correctly when pointing straight up.
Then I took 115 degrees / 90 degrees to get the compensation angle which is 1.277777777777778 but then I hit a wall.
The script I’m using is based on a Java Script created by Dusk. Here is the code:
public Transform target;
public float camDistance;
public float rightZPosition;
public float leftZPosition;
private float defaultPositionX;
private float defaultPositionY;
public bool extraRotation = false;
private float angleExtra;
private Vector3 mousePos;
private Vector3 objectPos;
public float angle;
void Start(){
defaultPositionX = target.transform.localPosition.x;
defaultPositionY = target.transform.localPosition.y;
}
void Update()
{
if( transform.rotation.y == 0){ // If player is facing to the right
// Flips the target object so that it faces the correct way
if(target.position.z != rightZPosition){
target.transform.localPosition = new Vector3(defaultPositionX, defaultPositionY, rightZPosition);
}
mousePos = Input.mousePosition;
mousePos.z = camDistance;
objectPos = Camera.main.WorldToScreenPoint(target.position);
mousePos.x = mousePos.x - objectPos.x;
mousePos.y = mousePos.y - objectPos.y;
angle = Mathf.Atan2(mousePos.y, mousePos.x) * Mathf.Rad2Deg;
// Applies extra degrees if true
if(extraRotation){
angleExtra = angle * 1.277777777777778f;
}
if(extraRotation){ // Rotates the target object on Z axis (with extra degrees)
target.rotation = Quaternion.Euler(0, 0, angleExtra);
}else{ // Rotates the target object on Z axis (normal degrees)
target.rotation = Quaternion.Euler(0, 0, angle);
}
}else{ // If player is facing to the left
// Flips the target object so that it faces the correct way
if(target.position.z != leftZPosition){
target.transform.localPosition = new Vector3(defaultPositionX, defaultPositionY, leftZPosition);
}
mousePos = Input.mousePosition;
mousePos.z = camDistance;
objectPos = Camera.main.WorldToScreenPoint(target.position);
mousePos.x = mousePos.x - objectPos.x;
mousePos.y = mousePos.y - objectPos.y;
angle = Mathf.Atan2(mousePos.y, mousePos.x) * Mathf.Rad2Deg;
// Applies extra degrees if true
if(extraRotation){
// THIS PART IS THE ONE I'M HAVING PROBLEMS WITH!
angleExtra = angle -25f; //aligns correct if pointed straight up
}
if(extraRotation){ // Rotates the target object on Z axis (with extra degrees)
target.rotation = Quaternion.Euler(180, 0, -angleExtra);
}else{ // Rotates the target object on Z axis (normal degrees)
target.rotation = Quaternion.Euler(180, 0, -angle);
}
}
}
Thanks in advance!