# Moving Obstacles

Hey guys, I am trying to make some moving obstacles in my game. I have 15X scale ground and I want to move them from side to side (-7.5x to 7.5x and then to the opposite side) I wrote some code but I have two issues with it:

1. It takes a few seconds until the obstacles get momentum and really move from side to side
2. If I make more then one obstacle they moving weird and different

the obstacles are cubes, as you can see in the picture

and this is the code I wrote

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

public class MoveObs : MonoBehaviour
{

``````public float sidewayForce = 30f;

static float dir;
public GameObject Mobs;
public Rigidbody RBMObs;

void Start()
{

RBMObs = Mobs.GetComponent<Rigidbody>();
if (RBMObs.position.x >= 0f)
{
dir = 1;

}

if (RBMObs.position.x < 0f)
{
dir = -1;

}

}

void FixedUpdate()
{
Move();

}

public void Move()
{
if (RBMObs.position.x > 6f)
{

// RBMObs.velocity = Vector3.zero;
//   RBMObs.angularVelocity = Vector3.zero;
dir = -1;
}

if (RBMObs.position.x < -6f)
{
// RBMObs.velocity = Vector3.zero;
// RBMObs.angularVelocity = Vector3.zero;
dir = 1;
}

RBMObs.AddForce( dir * sidewayForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);

}
``````

}

Why is it happening? Thank you all for the help

If you want the obstacle to move at a fixed speed along an axis, then you don’t want to use AddForce. It will add a force, and keep going until it loses the momentum over a duration. You can’t specify the point for it to stop, and it isn’t designed to move between specific points.

You could use MovePosition via the rigidbody, or alternatively use transform.Translate or even Vector3.MoveTowards. If you want the speed to increase or decrease, you can always increase/decrease the speed over time or at a specific point whilst it moves from point A to B.