How to rotate player with joystick in 2d?

I’m new in unity and I cant get it to work properly. I’m using this free joystick from the asset store: Joystick Pack | Input Management | Unity Asset Store

My problem is, that if I move the first joystick, to move the player around, the x, y and the z are rotating towards the center. I don’t know how to fix this.

Heres my code (joystick is to move the player and joystick2 is to rotate the player):

void Start()
{
    InvokeRepeating("Shoot", 0, firerate);
    rb = GetComponent<Rigidbody2D>();
}
float horizontalmove = 0f;
float verticalmove = 0f;
float speed = 3f;
float bulletspeed = 10f;
float firerate = 1f;

void Update()
{
    //Rotate
    transform.rotation = Quaternion.LookRotation(player.transform.position, joystick2.Direction);
    //Move
    horizontalmove = joystick.Horizontal * speed;
    verticalmove = joystick.Vertical * speed;
    Vector3 move = new Vector3(horizontalmove, verticalmove);
    rb.velocity = move;
    //Shoot
    if (joystick2.Horizontal > 0.5f || joystick2.Vertical > 0.5f || joystick2.Horizontal < -0.5f || joystick2.Vertical < -0.5f)
    {
        shooting = true;
    }
    else shooting = false;

    
}

void Shoot()
{
    if (!shooting) return;
    Rigidbody2D clone;
    clone = Instantiate(bullet, player.transform.position, Quaternion.LookRotation(player.transform.position, joystick2.Direction)) as Rigidbody2D;
    Vector3 directiontoshoot = joystick2.Direction;
    clone.velocity = directiontoshoot * bulletspeed;
}

1 Answer

1

Try

Vector2 dir = new Vector2(transform.position.x - player.transform.position.x, transform.position.y - player.transform.position.y); 

transform.up = dir;