- Home /
Whats wrong with this script?
this is a moving platform script. it wont work..
public Vector3 pointA;
public Vector3 pointB;
public float speed;
void Start () {
gameObject.transform.position = pointA;
}
// Update is called once per frame
void Update () {
if (gameObject.transform.position == pointA) {
gameObject.transform.position = Vector3.MoveTowards(gameObject.transform.position, pointB, speed * Time.deltaTime);
}
else if (gameObject.transform.position == pointB) {
gameObject.transform.position = Vector3.MoveTowards(gameObject.transform.position, pointA, speed * Time.deltaTime);
}
}
I get no errors. the platform just wont move..
Value of speed is? Undefined so probably 0. Value of pointA and pointB is? Undefined.
Is this script on the platform object?
What are the chances of the platform being exactly on the point defined by your vectors? Very little I shall tell thee.
i was setting the value in the inspector.. :) The script was on the object. The question has been solved :)
Answer by troien · Feb 14, 2015 at 11:02 AM
That is because you tell your platform to move towards pointB. So the first time you execute the Update loop, your position is equal to PointA and your platform will move a tiny little bit towards pointB, the next time you execute the Update loop, your position is not equal to PointA or pointB. Instead it is some Point in between, and thus your Update loop won't do anything after that...
I would suggest to change your code to something like this...
public Vector3 pointA;
public Vector3 pointB;
public float speed;
private Vector3 currentTarget;
void Start ()
{
transform.position = pointA;
currentTarget = pointB;
}
// Update is called once per frame
void Update ()
{
transform.position = Vector3.MoveTowards(transform.position, currentTarget, speed * Time.deltaTime);
// If we reach pointA or pointB, change target
if (transform.position == currentTarget)
{
if (currentTarget == pointA)
currentTarget = pointB;
else
currentTarget = pointA;
}
}
If it really doesn't even move the first Update loop, then either pointB is equal to pointA, speed is 0, or you have your script disabled... Either way, the problem I described above will still happen.
that kind of works. but say if my point B x value is 56 it will only go to 54.99991 or something so it wont go all the way thus returning to point a.. nvm got it thanks for your help
Your answer
Follow this Question
Related Questions
Moving Physics Objects With Character Controller? 2 Answers
Rotate multiple objects around or rather move them on the surface of another object 1 Answer
Player Controls 0 Answers
How do I stop a player from bouncing on a descending platform? 1 Answer
How to 'do stuff' to specific cross sections of 3D polygons 1 Answer