A
A
Amffore2017-10-19 21:00:25
Unity
Amffore, 2017-10-19 21:00:25

Is such a code appropriate?

I would like to hear the expert opinion of more experienced programmers.
The essence of the code is that with each click, the object changes the direction of movement. Is this approach appropriate and what problems might arise? Is there a more rational solution to this problem?
So far, from the obvious problems, a little noticeable, spontaneous increase in the speed of the object for a fraction of a second is found.

public float speed; //скорость объекта

    private Rigidbody2D rb2d;

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

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            rb2d.velocity = Vector2.right * speed * Time.deltaTime;
            
            if (rb2d.position.x > 0)
            {
                rb2d.velocity = Vector2.left * speed * Time.deltaTime;
            }

            if (rb2d.position.x < 0)
            {
                rb2d.velocity = Vector2.right * speed* Time.deltaTime;
            }
        }
        
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Griboks, 2017-10-19
@Amffore

if (Input.GetMouseButtonDown(0)) rb2d.velocity*=-1;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question