0
votes

I'm making a 2.5D plataform game and I can't get the rotation of the player right. I just want it to rotate on the X-axis while the player move towards left and right. My movement script is this:

      if (isWalking)
    {
        transform.Rotate(0, facingDir, 0);
        isWalking = false;
    }
    else { }

    if (Input.GetKey(KeyCode.Space))
        GetComponent<Rigidbody>().velocity = new Vector2(GetComponent<Rigidbody>().velocity.x, jumpHeight);

    if (Input.GetKey(KeyCode.A)){
        GetComponent<Rigidbody>().velocity = new Vector2(-speedHeight, GetComponent<Rigidbody>().velocity.y);
        facingDir = 180;
        isWalking = true;
    }

    if (Input.GetKey(KeyCode.D))
    {
        GetComponent<Rigidbody>().velocity = new Vector2(speedHeight, GetComponent<Rigidbody>().velocity.y);
        facingDir = 0 ;
        isWalking = true;
    }

The best way I could rotate it was by transform.rotate(0,180,0) and (0,0,0), but then it keeps rotating non stop, how can I tell what direction the player is moving on the X-axis so I can transform.rotate properly?

1

1 Answers

1
votes
transform.forward

This should give you the direction the player is moving in. You can use

transform.LookAt(target);

to orient the player in a specific direction. The main issue is that you are trying to update the direction in the GetKey function which returns true while the key is held down. This results in the character rotating constantly, you have avoided this by using an additional check. You could use Lookat instead in the following manner:

GetComponent<Rigidbody>().velocity = new Vector2(-speedHeight, GetComponent<Rigidbody>().velocity.y);

transform.LookAt(transform.position+new Vector3(GetComponent<Rigidbody>().velocity.x,0,GetComponent<Rigidbody>().velocity.y));

There are better ways to do this but this should solve your problem.