- Home /
Rotate GameObject Z axis only relative to Joystick
Hi, I'm making a mobile 2D game for Android.
The movement system is a joystick that gets created whenever the user touches the screen. Relatively to the position of the first touch, when the finger is moved the GameObject is moved.
I need to make it so that the GameObject faces either: -The direction of the touch, considering the joystick -The direction of movement
Here's the joystick script
public class InvisibleMovingJoystick : MonoBehaviour
{
public GameObject phage;
public float speed = 1.0f;
private bool touchStart = false;
Vector2 pointA;
Vector2 pointB;
private Rigidbody2D rb2d;
void Start()
{
rb2d = phage.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
if(Input.touchCount == 1)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began)
{
pointA = touch.position;
}
if (touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary)
{
pointB = touch.position;
touchStart = true;
}
else
{
touchStart = false;
}
}
}
private void FixedUpdate()
{
if(touchStart == true)
{
Vector2 offset = pointB - pointA;
Vector2 direction = Vector2.ClampMagnitude(offset, 1.0f);
moveCharacter(direction);
}
}
void moveCharacter(Vector2 direction)
{
rb2d.MovePosition(rb2d.position + direction * speed * Time.deltaTime);
}
I tried this:
float angle = Mathf.Atan(direction.y, direction.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward )
But it doesn't really work properly.
I'm very bad at math regarding angles, could you give me a hand?
Thanks
Comment
Your answer
Follow this Question
Related Questions
Mobile joystick not moving player 0 Answers
GUI Joystick 1 Answer
Scaling Script? 1 Answer
Importing Facebook SDK on project makes the build crash on Android 2 Answers
Game looks different on device compared to Game View 0 Answers