R
R
Ruslan Stupin2017-04-26 20:48:25
Game development
Ruslan Stupin, 2017-04-26 20:48:25

How to implement player movement restriction on Unity3D?

Hello)
I am a beginner developer.
I'm trying to implement a TopDown player movement. The player moves parallel to the coordinate axes. Please help make it so that he can only change direction by 90 degrees. From moving down to the right or left. From movement to the right down or up.
Here are my achievements (if you give advice on them it will be cool))):

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

public class PlayerController : MonoBehaviour {

  private float horizontal;
  private float vertical;
  public float speed = 1f;
  public float time = 0.1f;

  public bool right = true;
  public bool left = true;
  public bool up = true;
  public bool down = true;

  private Rigidbody2D rb;

  void Start () {
    rb = GetComponent<Rigidbody2D> ();
  }
  
  // Update is called once per frame
  void Update () {

    horizontal = Input.GetAxis("Horizontal");
    vertical = Input.GetAxis("Vertical");

    if (horizontal > time && (up || down)) {
      rb.velocity = (new Vector2 (1, 0)) * speed;
      right = true;
      left = false;
      up = false;
      down = false;

    }
    if (horizontal < time & (up || down)) {
      rb.velocity = (new Vector2 (-1, 0)) * speed;
      right = false;
      left = true;
      up = false;
      down = false;
    }
  
    if (vertical > time & (right || left)) {
      rb.velocity = (new Vector2 (0, 1)) * speed;
      right = false;
      left = false;
      up = true;
      down = false;
    }
    if (vertical < time & (right || left)) {
      rb.velocity = (new Vector2 (0, -1)) * speed;
      right = false;
      left = false;
      up = false;
      down = true;
    }
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alibek Beldinov, 2017-05-24
@Khan_RA

You will need to change your code a bit. I advise you to make it so that your character can only go forward or backward. When you press the buttons left, right, turn your character.
https://docs.unity3d.com/ScriptReference/Rigidbody...
https://docs.unity3d.com/ScriptReference/Quaternio...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question