E
E
Efim Efimov2019-09-01 20:39:01
C++ / C#
Efim Efimov, 2019-09-01 20:39:01

How to make a character turn in the direction of movement in Unity?

Help, I want the character to turn in the direction he is walking. 2D game.
Also, if it's not difficult, tell me how to fix the fact that the character makes jumps like in Flappy Bird (can jump during the jump).
If anything, I just started learning C# and Unity.
Here is the movement code:

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

public class Player : MonoBehaviour {

    Rigidbody2D rb;

    void Start() {
        rb = GetComponent<Rigidbody2D>();
    }

    void Update() {
        if (Input.GetKeyDown (KeyCode.Space)) {
            jump();
        }
    }

    void FixedUpdate() {
        rb.velocity = new Vector2(Input.GetAxis("Horizontal") * 6f, rb.velocity.y);
    }

    void jump() {
        rb.AddForce(transform.up * 5f, ForceMode2D.Impulse);
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
Griboks, 2019-09-01
@Griboks

the character turned in the direction in which he was walking.

void FixedUpdate() {
        rb.velocity = new Vector2(Input.GetAxis("Horizontal") * 6f, rb.velocity.y);
        if(rb.velocity>0) RotateRight();
else RotateLeft();
    }

void Update() {
        if (Input.GetKeyDown (KeyCode.Space) && CanJump()) {
            jump();
        }
    }

C
CHIDWI, 2019-09-05
@CHIDWI

To avoid doublejump add a boolean variable. Before jumping, you check whether the character is jumping or not. In the jump function, you make it true. And when landing through OnCollision, for example, you make it false again.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question