I just started learning Unity and C#
I’m trying to move my sprite over a line I draw on-screen with the mouse, it looks like the script is more or less working, but I would like to keep the GameObject at the position it is at the end of the line when it finishes the movement.
As you can see from the picture attached every time it finishes the animation it goes back to its original position (0,0).
How can I stop this behavior?
using System.Collections;
using System.Collections.Generic;
using Unity.Burst.Intrinsics;
using Unity.VisualScripting;
using UnityEngine;
public class Follow : MonoBehaviour
{
private LineRenderer lineRenderer;
public GameObject objectToMove;
public float speed = 5f;
private Vector3[] positions = new Vector3[397];
private Vector3[] pos;
private int index = 0;
private GameObject toFollow;
DrawLines drawLines;
[SerializeField] GameObject gameController;
private bool isDrawingLineDone = false;
// Start is called before the first frame update
void Awake()
{
drawLines = gameController.GetComponent<DrawLines>();
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0) == true) // caso linea si e click
{
clearLines();
}
if (drawLines.isLinePresent == true && Input.GetMouseButtonUp(0) == true)
{
if (!isDrawingLineDone)
{
pos = GetLinePointsInWorldSpace();
objectToMove.transform.position = pos[index];
isDrawingLineDone = true;
}
}
if (isDrawingLineDone == true && finishMove == false)
{
Move();
}
else if (isDrawingLineDone == true && finishMove == true)
{
objectToMove.transform.position = pos[pos.Length - 1];
}
}
Vector3[] GetLinePointsInWorldSpace()
{
//Get the positions which are shown in the inspector
toFollow = GameObject.Find("Linea");
lineRenderer = toFollow.GetComponent<LineRenderer>();
lineRenderer.GetPositions(positions);
//the points returned are in world space
return positions;
}
// MOve the gameObject
private bool finishMove = false;
void Move()
{
objectToMove.transform.position = Vector3.MoveTowards(objectToMove.transform.position,
pos[index],
speed * Time.deltaTime);
if (objectToMove.transform.position == pos[index])
{
index += 1;
if (objectToMove.transform.position == pos[pos.Length - 1])
{
print("DONE");
finishMove = true;
}
}
if (index == pos.Length)
{
index = 0;
}
}
// delete other line if there is
private GameObject toDestroy;
void clearLines()
{
toDestroy = GameObject.Find("Linea");
Destroy(toDestroy);
drawLines.isLinePresent = false;
}
}