I made a script to move an object in the X axis. I got it to move to the right but can’t get it to move in the opposite direction once it gets ti a certain position in game. Here is the script I made.
#pragma strict
var speed : float = 4.0;
function Update () {
transform.Translate(Vector3(speed,0,0) * Time.deltaTime);
if(transform.position.x == -36){
transform.Translate(Vector3(speed,0,0) * Time.deltaTime);
}
else if(transform.position.x == -25){
transform.Translate(Vector3(speed,0,0) * Time.deltaTime);
}
}
Any help would be grateful.
It would be practically impossible for the x value to be exactly -25 or -36. Use >= and <= (greater than or equal to, less than or equal to).
Store the speed in a separate variable, change the value of that variable based on the results of the conditionals.
pragma strict
public var speed : float = 4.0;
private var currSpeed : float;
function Start()
{
currSpeed = speed;
}
function Update()
{
if ( transform.position.x >= -25 )
{
currSpeed = -speed;
}
else if ( transform.position.x <= -36 )
{
currSpeed = speed;
}
transform.Translate( Vector3(currSpeed,0,0) * Time.deltaTime );
}
Edit : For future help, please format your code. You can do this by highlighting all your code, then clicking the 10101 button at the top of the edit window.