- Home /
How to adjust the speed of an object?
I got this script that makes it so then a game object travels through certain transforms. I didn't make this and I'm not familiar with C#, so I don't know how to make a variable that adjusts the speed. So, can anybody let me know how I can change the speed with a variable? Here is the script:
public class randomMovement : MonoBehaviour {
//Here I am defining a new array called "targets", with an array length of 3.
//This means that there will be 3 transforms in my array.
//I can assign these in the inspector window.
public Transform[] targets = new Transform[3];
//Here I am defining an int variable which i can use to change the current "targets" transform to use.
public int curTarget = 0;
void Update() {
//Check if we are within 1 unit of our target (reduces risk of error - object could miss target which is what causes yours to circle the target)
if((transform.position - targets[curTarget].transform.position).magnitude < 1f) {
//When we are within one unit of target, switch to the nex target(or the next transform in the array).
curTarget++;
//When our current target reaches the length of the array, we will loop it back to 0 so that it repeats.
if(curTarget > 2) {
curTarget = 0;
}
}
//Move forwards
transform.Translate(Vector3.forward * 3.0f * Time.deltaTime);
//Always look at the current target
transform.LookAt(targets[curTarget].position);
}
}
Answer by bigbat · Jun 08, 2013 at 08:09 PM
just add a public var for movement speed (i.e. add this line of code at line 6 of your code : )
public float MoveSpeed = 3.0f;
and change line 20 to this :
transform.Translate(Vector3.forward * MoveSpeed * Time.deltaTime);
Thank you so much! The new script works fine!
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
How do I change my speed based on certain events? 0 Answers
Change output rotation of this Lookat script? 2 Answers
How to Set the Game Speed Based on the Player's Current Score? 1 Answer