I am trying to move an object that has a rigidbody 2D attached between two points in space, when the object reaches a point it has to begin moving towards another one. I have been using this code:
void Update ()
{
transform.position = Vector2.MoveTowards (transform.position, patrolPoints [pointToReach].transform.position, moveSpeed * Time.deltaTime);
if (transform.position == patrolPoints[pointToReach].transform.position)
{
if (pointToReach == patrolPoints.Length - 1)
{
pointToReach = 0;
}
else
{
pointToReach++;
}
}
}
How can I do the same thing by moving the Rigidbody2D? Is there something similar to MoveTowards than I can use?
Thanks in advance
You can use MovePosition
method on a rigidboy in a FixedUpdate
method. However you will have to test if the object arrived to its destination by testing the distance from its current point to the target point:
void Awake() {
rb = GetComponent<RigidBody2D>();
}
void FixedUpdate() {
Vector3 dir = patrolPoints[pointToReach].transform.position - rb.position;
dir.Normalize();
rb.MovePosition(rb.position + dir * Time.fixedDelta * moveSpeed);
float sqrMag= (patrolPoints[pointToReach].transform.position - rb.position).sqrMagnitude;
if (sqrMag > 0.1) {
// You have reached your destination
rb.position = patrolPoints[pointToReach].transform.position;
}
}
This might not be the best approach but it should get you started. If you find more efficient please share…