- Home /
Moving 2D sprite along a path
I have 10 x 10 grid with some items (Gems). Player drags cell Item from one place to another. I have already found Vector3 positions where I should move my game object. As I understand I should do this in Update method by calling Vector3.MoveTowards or Vector3.Lerp or changing position directly, but I have started using Unity not so long ago and I didn't quite get how should I do this. So I have List with positions where I should move my object (Debug.DrawLine)
How can I successively move Item from one point to another and what method I should use to do this?
UPD. Seems this is working for me. Maybe someone have more correct way to do this
void Update () {
if (currentItem != null) {
currentItem.transform.position = Vector3.MoveTowards(currentItem.transform.position, nextCellPosition, Time.deltaTime * 4.0f);
if (currentItem.transform.position == nextCellPosition) {
activePath.Points.RemoveAt(0);
if (activePath.Length > 1) {
nextCellPosition = cells[activePath.Points[1].y, activePath.Points[1].x].transform.position;
} else {
cells[activePath.Points.First().y, activePath.Points.First().x].Item = currentItem;
currentItem = null;
}
}
}
}
Do you mean actually moving along a path over time or just changing the position?
If the path is known (i.e. this question is not about searching out a viable path), then the movement is just a waypoint movement. There are lots of posts on UA about waypoints, plus I believe there is at least one waypoint script in the Unity Wiki.