Hi, very new in C# and Unity, I’m writing my first script to move my Player along a line drawn with a mouse.
So basically my script allows the player to draw the line with the mouse, once I finish moving the mouse I start to move the player with rigidbody2d.MovePosition().
Here is the issue:
if I move the mouse slowly or fast, the points of my line render are far or close to each other causing the MovePosition to move the player faster or slower.
Is there any way to modify the speed? How could I do this task in order to keep constant speed along the line?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMove : MonoBehaviour
{
private Rigidbody2D rb;
public LineRenderer lr;
private Vector2 velocity = new Vector2(1.75f, 1.1f);
//Not customizable:
private float timer = 0;
private int currentWayPoint = 0;
private int wayIndex;
private bool move;
private bool touchStartedOnPlayer;
public List<GameObject> wayPoints;
public GameObject wayPoint;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
lr.enabled = false;
wayIndex = 1;
move = false;
touchStartedOnPlayer = false;
}
public void OnMouseDown()
{
lr.enabled = true;
touchStartedOnPlayer = true;
lr.SetPosition(0, transform.position);
}
public void Update()
{
if (Input.GetMouseButton(0) && touchStartedOnPlayer)
{
Vector2 worldMousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
GameObject newWayPoint = Instantiate(wayPoint, position: worldMousePos, Quaternion.identity);
wayPoints.Add(newWayPoint);
lr.positionCount = wayIndex + 1;
lr.SetPosition(lr.positionCount - 1, worldMousePos);
timer = 0;
wayIndex++;
}
timer += Time.deltaTime;
if (Input.GetMouseButtonUp(0))
{
touchStartedOnPlayer = false;
move = true;
}
}
private void FixedUpdate()
{
if (move && wayPoints.Count > 1)
{
rb.MovePosition(wayPoints[currentWayPoint].transform.position);
if (transform.position == wayPoints[currentWayPoint].transform.position)
{
currentWayPoint++;
}
if (currentWayPoint == wayPoints.Count)
{
move = false;
wayIndex = 1;
currentWayPoint = 0;
wayPoints.Clear();
}
}
}
}