- Home /
Is there a way I can add drawing mechanic like in "line rider" for a 3D game?
So, I am making a 3D game (it's actually a 2D platformer with 3D components), but the drawing script I am using works for 2D scenes only, any ideas how to implement it in 3D? This is the line prefab scirpt.
using System.Linq;
using System.Collections.Generic;
using UnityEngine;
public class Line : MonoBehaviour
{
public LineRenderer lineRenderer;
public EdgeCollider2D edgeCol;
List<Vector2> points;
public void UpdateLine(Vector2 mousePos)
{
if (points == null)
{
points = new List<Vector2>();
SetPoint(mousePos);
return;
}
if (Vector2.Distance(points.Last(), mousePos) > .1f)
SetPoint(mousePos);
}
void SetPoint(Vector2 point)
{
points.Add(point);
lineRenderer.positionCount = points.Count;
lineRenderer.SetPosition(points.Count - 1, point);
if (points.Count > 1)
edgeCol.points = points.ToArray();
}
}
and this is the line generator script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LineCreator : MonoBehaviour
{
public GameObject linePrefab;
Line activeLine;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
GameObject lineGO = Instantiate(linePrefab);
activeLine = lineGO.GetComponent<Line>();
}
if (Input.GetMouseButtonUp(0))
{
activeLine = null;
}
if (activeLine != null)
{
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
activeLine.UpdateLine(mousePos);
}
}
}
Ps: The scripts are from Brackeys channel.
Thank you
First of all, change Vector2
everywhere to Vector3
and the line will be in 3D. However, it you will also have to specify the third coordinate, z. I recommend to either set it to a multiple of Camera.main.forward
so that you always draw in front of the camera, or use raycasting from the camera to get a more precise world point, and pass that:
RaycastHit hit;
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit)) {
Vector3 pos = hit.point - Camera.main.forward * 0.01f; // moving point towards camera to avoid z-fighting
activeLine.UpdateLine(pos);
}
Thank you for your reply, I tried what you said, I have 2 problems now:
First I don't know what to replace the edge collider 2D with.
Second, the Camra.$$anonymous$$ain.Forward, won't work, forwward works only with transform, should I add another library or did you mean camera.main.transform.forward?
Thanks again :)
Yes he means Camera.main.transform.forward. The other question is tricky. Depending on your game, but most likely you should use box colliders for the different lines. If there are a lot of curves in your line or your geometry is more complex, you'd have to look into changing the mesh using the mesh api. https://docs.unity3d.com/ScriptReference/$$anonymous$$esh.html
Your answer
Follow this Question
Related Questions
Free Look Camera Pivot 1 Answer
Locking the Z-axis based on direction 0 Answers
Should 2.5D use 3D or 2D settings ? 3 Answers
2D or 3D settings for a 2.5D game? 2 Answers