Hi folks,
I’ve got a problem and I hope you people can help me. I want to draw a line and after I finished drawing, I want the player to follow it. It’s that simple to explain, but not to program… (for me^^)
My code so far:
GameController.cs:
using UnityEngine;
public class GameController : MonoBehaviour
{
public LineRenderer LinePrefab;
PathGameObject pathGameObject;
private void Awake()
{
}
void Start()
{
}
private void Update()
{
if (Input.GetButtonDown("Fire1"))
{
// Click, so start drawing a new line.
pathGameObject = null;
}
if (Input.GetButton("Fire1"))
{
// Mouse is still down and we are dragging, so keep drawing.
Draw(Input.mousePosition);
}
}
public void Draw(Vector3 position)
{
// Create a plane and see where the mouse click intersects it.
Plane plane = new Plane(Camera.main.transform.forward * -1, position);
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (plane.Raycast(ray, out float distance))
{
if (pathGameObject == null)
{
// Starting a new line. Instantiate our "Path Object"
pathGameObject =
UnityEngine.Object.Instantiate(LinePrefab).GetComponent<PathGameObject>();
}
else
{
// TODO: Check distance between points. This just adds all of them, even
// if you hold the mouse still.
Vector3 hitpoint = ray.GetPoint(distance);
pathGameObject.AddPosition(hitpoint);
}
}
}
}
PathGameObject.cs:
using System.Collections.Generic;
using UnityEngine;
public class PathGameObject : MonoBehaviour
{
List<Vector3> points = new List<Vector3>();
LineRenderer lineRenderer;
void Start()
{
}
private void Awake()
{
lineRenderer = GetComponent<LineRenderer>();
}
void Update()
{
}
public Vector2 GetPosition(int index)
{
return points[index];
}
public void AddPosition(Vector3 position)
{
points.Add(position);
lineRenderer.positionCount = points.Count;
lineRenderer.SetPositions(points.ToArray());
}
public int Count()
{
return points.Count;
}
}
The LinePrefab got the PathGameObject.cs attached and a Line Renderer Component and then I created an empty object in my scene and attached the GameController.cs on it.
What my game does so far is drawing a line and nothing else, because I don’t know how to develop a player following the line.
Can you help me?
Greets,
One