0
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ What is the object? How should it interact with the rest of the game? What's your end goal? \$\endgroup\$ – Vaillancourt May 3 at 17:47
  • \$\begingroup\$ @Vaillancourt it is a trap on a floor that moves in certain range. \$\endgroup\$ – Nouman May 3 at 18:37
0
\$\begingroup\$

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.
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.