H
H
Haraz2021-05-29 09:22:03
Unity
Haraz, 2021-05-29 09:22:03

How to make a character rotate in the direction of movement in Unity2d?

Help, I want the character to turn in the direction he is walking. 2D game.
Initially looking to the left.
Here is the code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerContrl2 : MonoBehaviour
{
    public Rigidbody2D rb;
    public Vector2 moveVector;
    public float speed = 10f;
    void Start()
    {
        rb.GetComponent<Rigidbody2D>();
    }


    void Update()
    {
        walk();
        Jump();
        CheckingGround();
    }
    void walk()
    {
        moveVector.x = Input.GetAxis("Horizontal");
        rb.velocity = new Vector2(moveVector.x * speed, rb.velocity.y);
    }

    public float jumpForce = 7f;
    void Jump()
    {
        if (Input.GetKeyDown(KeyCode.Space) && onGround)
        {
            //rb.velocity = new Vector2(rb.velocity.x, jumpForce);
            rb.AddForce(Vector2.up * jumpForce);
        }
    }

    public bool onGround;
    public Transform GroundCheck;
    public float checkRadius = 0.5f;
    public LayerMask Ground;
    void CheckingGround()
    {
        onGround = Physics2D.OverlapCircle(GroundCheck.position, checkRadius, Ground);
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Edward Treit, 2021-05-30
@EdMSL

The most primitive way (and therefore not the best).
We create a method:

private void Flip()
    {
        if (Input.GetAxisRaw("Horizontal") == 1)
        {
            transform.localScale = new Vector3(1, 1, 1);
        } else if (Input.GetAxisRaw("Horizontal") == -1)
        {
            transform.localScale = new Vector3(-1, 1, 1);
        }
    }

In Update we write:
if (Input.GetAxis("Horizontal") != 0) {
    Flip();
}

In other words, we simply mirror the sprite along the x-axis, changing the value between 1 and -1.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question