# How do you make an object go left and right?

 0 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 { } } `````` more ▼ asked Jan 07 '11 at 08:36 AM GTS925 11 ● 5 ● 5 ● 7 add new comment (comments are locked) 10|3000 characters needed characters left ▼ Viewable by all users

 0 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. more ▼ answered Jan 07 '11 at 12:02 PM Graham Dunnett ♦♦ 11.8k ● 11 ● 20 ● 64 add new comment (comments are locked) 10|3000 characters needed characters left ▼ Viewable by all users

By Email:

Topics:

x1278
x1095
x498
x24
x22

asked: Jan 07 '11 at 08:36 AM

Seen: 3128 times

Last Updated: Jan 07 '11 at 08:36 AM