Reputation: 83
Plank unable to move when i used Vector3.MoveTowards method. I am not entirely sure why. Anyone kind enough to have a look?
public class BrickMoveVErtical : MonoBehaviour
{
public Vector3 positionOne, positiontwo, nextposition;
public Transform plankTranform;
public Transform positionBTransform;
public float speed;
void Start ()
{
positionOne = plankTranform.localPosition;
positiontwo = positionBTransform.localPosition;
nextposition = positiontwo;
}
void Update ()
{
move();
}
private void move()
{
plankTranform.localPosition = Vector3.MoveTowards(positionOne,nextposition,Time.deltaTime*speed);
if(Vector3.Distance(plankTranform.localPosition,nextposition)<0.1)
changeMovementPlank();
}
void changeMovementPlank()
{
nextposition = nextposition != positionOne ? positionOne : positiontwo;
}
}
Upvotes: 1
Views: 406
Reputation: 3326
This one of the same mistakes you just made in the last question. Vector3
is a value type, which means if you do this:
private v1 = new Vector3(3, 3);
private v2 = v1; // v2 has now *copied* the value of v1
v1 = new Vector(0, 0); // v1 is now (0, 0), but v2 is still (3, 3)
What you're doing is effectively that. If you want a variable-like thing that will always give the latest value, use a property, like this:
public Vector3 positionOne
{
get { return plank.transform.position; }
set { plank.transform.position = value; }
}
This will always return the correct and updated value and when you set this you will actually change the original value, not the copy.
Upvotes: 0
Reputation: 32597
You should use the current position as the current
argument:
plankTranform.localPosition = Vector3.MoveTowards(plankTranform.localPosition, nextposition,Time.deltaTime*speed);
^^^^^^^^^^^^^^^^^^^^^^^^^^^
Upvotes: 3