- Home /
figured it out myself
2D top-down multiple sprite rotation
So i am trying to make a character movement system that looks cool and i've run into a major problem. I have this 2D top-down character that consists of three sprites: head, body and legs. The head rotates towards the mouse using the atan2 function, the legs rotate if the angle between the head and legs is greater than 90 degrees, and the body is just half the angle between the head and legs. The problem is that the atan2 function jumps between -PI and PI, and instead of the legs continuing to follow the head, it acts as if the head got rotated the other way really quickly, which is not at all what i want. Please help, my brain is melting!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerController : MonoBehaviour {
float a;
float aH;
float aL;
float aB;
float t = 10f;
float legspace = Mathf.PI / 2;
public GameObject head;
public GameObject body;
public GameObject legs;
void Update () {
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
a = Mathf.Atan2(mousePos.y,mousePos.x);
if (a < 0) a += Mathf.PI * 2;
Quaternion a1 = Quaternion.Euler(0, 0, aH);
Quaternion a2 = Quaternion.Euler(0, 0, a);
Quaternion aHq = Quaternion.Slerp(a1, a2, t * Time.deltaTime);
aH = aHq.eulerAngles.z;
if ((aH - aL) > legspace) aL = aH - legspace;
else if ((aH - aL) < -legspace) aL = aH + legspace;
aB = ((aH - aL)) / -2 + aH;
legs.transform.rotation = Quaternion.Euler(0, 0, Mathf.Rad2Deg * aL);
body.transform.rotation = Quaternion.Euler(0, 0, Mathf.Rad2Deg * aB);
head.transform.rotation = Quaternion.Euler(0, 0, Mathf.Rad2Deg * aH);
}
}
Answer by Wolfride · Dec 16, 2018 at 03:28 AM
I mean... Can't you just parent all 3 pieces to an empty game object and just rotate that? Or you don't want them all to move at the same time and your problem is the head is moving too fast while everything else is fine? And if you just didn't have the head rotate as far, it would look really good as it.
The thing is that i want the player to continue turning one way, without that sudden jump on the right side. And i dont wanna limit the head movement either, i want him to be able to turn 360 freely without the sudden jump
Follow this Question
Related Questions
I have an animaiton problem about sprite loading. 0 Answers
Vector art Player 0 Answers
Crop/Mask a Sprite on runtime 0 Answers