- Home /
Why does this code not work?
I have this code for moving obstacles. I added (speed/100) to the MovePosition to make it a little slower. It works fine when speed is greater than 100, but the obstacle doesn't stop where it's supposed to if it is below 100.
public Rigidbody rb; public Transform Obstacle; public float speed; public Vector3 move; private Vector3 destinationChecker;
// Start is called before the first frame update
void Start()
{
destinationChecker = Obstacle.position + move;
}
// Update is called once per frame
void FixedUpdate()
{
rb.MovePosition(Obstacle.position + (move * Time.deltaTime * speed));
if (Obstacle.position == destinationChecker)
{
move = -move;
destinationChecker = Obstacle.position + move;
}
}
Can someone give me an explanation as to why this is happening?
Also, I just ran some tests and the code doesn't work when I try to move it along the z axis. Like 0, 0, 10 doesn't work. Can someone also tell me a way to fix this?
Answer by axlxi1 · Sep 03, 2020 at 05:24 AM
it's always better to checking if an GameObject has reached certain destination instead of checking if it's position is exactly equals to the destination you can check the distance between them is less than some small number for example in this case you instead of (Obstacle.position == destinationChecker) you can do this :
if (Vector3.Distance (Obstacle.position , destinationChecker) < .1f)
{
//you have reached your destination
}
Your answer
Follow this Question
Related Questions
My character cant jump 2 Answers
Shoot accuracy bar 1 Answer
Anyone could explain for me "Animator.GetCurrentAnimatorStateInfo(x)" command ? 2 Answers
Smooth jump script? 1 Answer