- Home /
Moving an object
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.
Answer by AlucardJay · Oct 22, 2013 at 01:55 PM
It would be practically impossible for the x value to be exactly -25 or -36. Use >= and
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.
If my answer helped, don't forget to accept it by clicking the tick under the thumbs, thanks.
http://video.unity3d.com/video/7720450/tutorials-using-unity-answers
Your answer
Follow this Question
Related Questions
how do i slowly translate a object to a other objects position 2 Answers
Match position of two object without making one a child of the other 4 Answers
transform.Translate but Transform has Rotation!=0 1 Answer
Object not moving,Object not moving in any direction 1 Answer
Move Object to location of Trigger? 1 Answer