- Home /
How do you make an object go left and right?
This is my script, it only goes left. How can I make it go left, then right?
void Update() {
this.transform.position += new Vector3(-1.0f, 0.0f, 0.0f) * Speed;
if (this.AIShoot == true)
{
Instantiate(Ballistic, this.transform.position, new Quaternion());
this.AIShoot = false;
AudioSource.PlayClipAtPoint(Sound, new Vector3(12.50f, 30.0f, 12.50f), 10.0f);
}
else
{
}
}
Answer by Graham-Dunnett · Jan 07, 2011 at 12:02 PM
Your object is moving left because you have a vector (-1,0,0) in your script. To make the object move right you'd use a vector (1.0f, 0.0f, 0.0f).
To make the object move left and then right, you need to decide when to make the switch. That could either be when the x value of the position is less than a certain value:
if (this.transform.position.x < 10.0f) {
// move right
} else {
// move left
}
or based on time, in which case you'd use Time.time.
However, typically in a game you want your objects to be moving and changing direction all the time. With this more complex requirement you are really better off using a simple state machine to control your object. The state could be a simple variable that takes on one of 3 values (0, 1 or 2) which mean the object is not moving, moving left, or moving right:
var state = 0;
void Update() { if (state == 2) { // move right } else if (state == 1) { // move left } else { // state is zero // don't move } }
This code just controls how the object moves. You can now have other code that sets the value of state, to control how the object moves. You could for example have an OnGUI function that has three buttons you can press to control which direction your object moves in. In your real game, however, you'd compute the state based on lots of things including time, where the object is, where an AI system wants the object to go to, or what keys, mouse or touch the player makes.
Note for the more advanced programmer, you'd probably want to use enums, as per http://stackoverflow.com/questions/287903/enums-in-javascript to represent the state of the object.