Hi I’m pretty new to Unity and not sure how to approach this problem.
I’m creating a 2D zip line building simulator/puzzle game for kids: given a set of predetermined “snap points,” a player should be able to draw zip line segments between snap points (by clicking and dragging the mouse from one snap point to another) to create a zip line course. The snap points are given so that the player can only build a zipline between those predetermined points and not just anywhere on the screen. This restriction is where I’m having trouble.
I’ve been able to create snap points as circular-shaped game objects and use the 2D line renderer to draw lines between snap points, but currently I can draw lines anywhere else on the screen too. How can I restrict the drawing of lines (by clicking and dragging the mouse) to only occur between two snap points and no where else on the screen?
Note1: Since i am inexperienced with Unity2D, i’ve made this script using a 3d scene. So if this do have a use for you, you only need to adapt it to your 2D project.
Note2: On this scene, a created snaps GOs and assing this script foreach.
Note3: Bare in mind that in this code, the lines do cross another snaps in order to reach their target.
using UnityEngine;
using System.Collections;
public class LineGenerator : MonoBehaviour
{
public GameObject emptyGO;
GameObject instantiatedGO;
GameObject currentSnap;
bool phase1;
Vector3 lineWantedPosition;
void Update ()
{
if (Input.GetButtonDown ("Fire1"))
{
Ray ray1 = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit1;
if(Physics.Raycast(ray1, out hit1, Mathf.Infinity))
{
if(hit1.collider.gameObject.CompareTag ("Snap")&& hit1.collider.gameObject == this.gameObject)
{
currentSnap = hit1.collider.gameObject;
phase1 = true;
instantiatedGO = (GameObject) Instantiate (emptyGO, currentSnap.transform.position, Quaternion.identity);
}
}
}
if (Input.GetButtonUp ("Fire1"))
{
Ray phaseRay = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit phaseHit;
phase1 = false;
instantiatedGO = null;
currentSnap = null;
if(Physics.Raycast(phaseRay, out phaseHit, Mathf.Infinity))
{
if(phaseHit.collider.gameObject == currentSnap || phaseHit.collider.gameObject.tag != "Snap")
{
Destroy (instantiatedGO);
}
}
}
if (phase1 == true)
{
MouseRayGenerator();
LinesSpawn();
}
}
void MouseRayGenerator()
{
if (phase1 == true)
{
Ray mouseRay = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit mouseHit;
if (Physics.Raycast (mouseRay, out mouseHit, Mathf.Infinity))
{
lineWantedPosition = new Vector3 (mouseHit.point.x, mouseHit.point.y, mouseHit.point.z);
}
}
}
void LinesSpawn ()
{
if(phase1 == true)
{
LineRenderer line;
line = instantiatedGO.GetComponent<LineRenderer>();
line.enabled = true;
Ray lineRay = new Ray (instantiatedGO.transform.position, lineWantedPosition);
line.SetPosition (0, lineRay.origin);
line.SetPosition(1, lineWantedPosition);
}
}
}
If this do not fits you, I hope it put you on the right track.