Getting an object two move between two objects continuously
I'm making a game where my Goal needs to move back and forth between two walls. I've tried troubleshooting this for hours but still can't find a good way of doing this. If someone could please explain some steps needed to make this happen I would be really grateful. It needs to 1.Move 2.When hitting wall go the opposite direction on the x axis 3.continue doing this until level is finished
Answer by ray2yar · Feb 15, 2019 at 11:46 PM
Try something like this:
 Int direction = 1;
 public Rigidbody RB;
 
 
 void Start ()
 {
     RB.velocity = //way you want it to go
 }
 
 void FixedUpdate()
 {
      //Do stuff
 }
 
 void OnCollisionEnter(Collision cool)
 {
     //First check if the object hit your wall
     //If it did then do this
     direction*=-1;
     RB.velocity = //vector3 * direction;
 }
 
              same answer, using kinematics, we cant use colliders to detect walls and the solution isn't elegant like the previous, I just encourage read it to learn other way, but use the @ray2yar as final solution, more general purpose (I just suggest, in case your later don't have perfect aligned walls change direction*=-1; by direction = -cool.GetContact(0).normal)
   Vector3 wallPosition1;
   Vector3 wallPosition2;
   float ballSpeed;
   float wayCompleted = 0;
   float step;
   bool inveseWay = false;
   void Start(){
           //Get the step to do each FixedUpdate
           step = (ballSpeed*Time.FixedDeltaTime) / (wallPosition2 - wallPosition1).magnitude;
   }
   void FixedUpdate()
   {
              transform.positon = Vector3.Lerp (wallPosition1, wallPosition2, wayCompleted);
             if (inveseWay){
                  wayCompleted -= step;
                  if (wayCompleted  < 0){
                        wayCompleted = 0;
                        inveseWay = false;
                  }
             }else{
                  wayCompleted += step;
                  if (1 < wayCompleted ){
                        wayCompleted = 1;
                        inveseWay = true;
                  }
            }
    }
 
                 Your answer
 
             Follow this Question
Related Questions
Moving cubes automatically on the y-axis 0 Answers
It lags when it collides. Help? :( 0 Answers
charactercontroller car acceleration and deceleration 0 Answers
Pick Up and Drop Script not functioning due to loophole 1 Answer
Values added during editor mode are removed when starting playmode 2 Answers