0

Suppose there is a small tile and I want an object to move on x axis on that tile back and forth. How can I make that object in that specific tile. My code is :

 Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
    rb = GetComponent<Rigidbody2D>();
}

// Update is called once per frame void Update() { rb.velocity = new Vector2(-3f, 0); }

As of now object moves left but I want it to start moving right and not go of the tile.

Nomi
  • 33
  • 7

1 Answers1

0

There are two ways to do it:

  1. To move object little by little every frame. I use this method to move units in my RTS game. In order to stop at wanted point I check every frame the distance left to target point, and if distance is small enough I stop the game object. In order to run code every frame write it in Update() function. To move little by little write small code into your Update() function:

    if (shouldMove==true)
    {
      transform.Translate(directionVector* speed);
    }
    

To check distance between two points I use:

Vector3.Distance(transform.position, positionOfTarget)

To stop moving just set variable shoudMove to false.

  1. Second method is to give objects rigid body velocity as you did. You need to do it only once so no need to put it in Update() function. But in order to stop you will still need to check distance as I wrote in previous option. When you need to stop - just set velocity to zero.
ShoulO
  • 499
  • 2
  • 6