Reverse Transform.translate

Hello, I am trying to make an object go the other way when it reach to x = -4. What I am doing wrong? Thanks in advance!

var speed = 0.5;

function Update ()

{

   transform.Translate  (Time.deltaTime * -speed,0,0,Space.World);

   if (transform.position.x < -4)
   {
	   transform.Translate  (Time.deltaTime * speed,0,0,Space.World);
   }

}

  1. You are moving in the normal direction no matter what.
  2. Its not the correct solution even if you wrapped your code in if else statements because your x positions value may never exactly be 4. Edit: Just noticed that in your question you are checking for equality but in your code you are checking if x is smaller.

Instead you should store the direction you want to move in and pass that to translate. Then check if the position is <= -4. If it is invert your stored direction. Try this instead. I think its the correct syntax for Unityscript. I’m used to C# now;

var speed = 0.5;
var direction = Vector3(-1,0,0);

function Update ()

{
   if (transform.position.x < -4)
   {
       direction = -direction;
   }
   transform.Translate  (direction * Time.deltaTime * speed, Space.World);
}

Thanks, worked this way:

var speed = 0.5;
var direction = Vector3(1,0,0);

function Update ()

{

  if (transform.position.x > 4)

  {

   direction = -direction;

  }

  transform.Translate  (direction * Time.deltaTime * speed, Space.World);

}

I don’t know why changing the negative 4 worked, but it worked.

Hello. I have had the same issue. I wasn’t able to reverse the translate.

I am reading strings from a CSV file of type:

-0.1
-0.2
0
+0.1

I check whether the first character is a “-”. If yes, i want to reverse the translate.

Right now, the Object keeps going into only one direction (positive). How can i accomplish this task?

Thanks in advance for any help.

void readCSV()
	{
		string[] records = csvFile.text.Split('

‘);
for(int i = 1; i < records.Length; i++)
{
string fields = records*.Split(’,');*

  •  	// Check whether the vector is negative (has a '-' sign in front)*
    
  •  	fieldFirst = fields[0];*
    
  •  	if(fieldFirst.Substring(0,1) == "-")*
    
  •  	{* 
    
  •  		Debug.Log ("-");*
    
  •  		direction = -direction;*
    

Direct_Opp_Quad.transform.Translate (0,0, -float.Parse(fields[0])*Time.deltaTime);

  •  		}*
    
  •  	else*
    
  •  	{*
    
  •  		Debug.Log ("+");*
    

Direct_Opp_Quad.transform.Translate (0,0, float.Parse(fields[0])*Time.deltaTime);

  •  	}*
    
  •  	}*
    

}