Reputation: 15
I'm trying to have this line here move along an axis each time I click it. This component is being generated with lineRenderer.
Extra: I need the line to move to the opposite side of where I clicked.
Can anyone help?
Best, IC
Upvotes: 0
Views: 3802
Reputation: 677
Here is an example achieving the basis of what you want (Clicking the line and repositioning), however it requires a 3D collider so add that to the GameObject, resize it appropriately, make sure to turn off Use World Space in the line renderer component, and then add this script.
using UnityEngine;
using System.Collections;
public class MoveLine : MonoBehaviour {
private LineRenderer line;
private Camera thisCamera;
private Ray ray;
private RaycastHit hit;
void Awake () {
line = GetComponent<LineRenderer>();
thisCamera = FindObjectOfType<Camera>().GetComponent<Camera>();
}
public void OnMouseDown () {
Vector3 mousePos = Input.mousePosition;
ray = thisCamera.ScreenPointToRay(mousePos);
if(Physics.Raycast(ray, out hit))
{
print (hit.collider.name);
line.transform.position = new Vector3(5, 5, 5); //Change to whatever position you need
}
}
}
OK, the functionality you want can be achieved several different ways. Here's how I would do it with minimal code changes to the script above:
Firstly remove the box colliders and 'MoveLine' script from your linerenderer gameobject, then add two empty child objects to it. Call one LeftSide and the other RightSide. Add one 3D boxcollider to each of these child objects (sides) and, as you may have guessed, the right box collider should be positioned so it covers the right side of the renderer and the left on the left side of the renderer (try not to let them overlap, but get as close as possible).
Now rename your MoveLine script to MoveLineLeft, duplicate it and rename the other to MoveLineRight. Do not forget to change the class names as well. Add 'MoveLineRight' to the 'LeftSide' gameobject (as you said you wanted a click on the left to move it to the right) and add 'MoveLineLeft' to the 'RightSide' gameobject.
Open both scripts; in 'MoveLineLeft' on the line where it says line.transform.position...etc. remove and add this instead:
line.transform.position = new Vector3(transform.position.x - 1, 0, 0);
in 'MoveLineRight' on the same line remove it again and add the following:
line.transform.position = new Vector3(transform.position.x + 1, 0, 0);
Extra Update Also change GetComponent to GetComponentInParent in the Awake function in both scripts to make sure your objects know where to get the line renderer from.
This should now give you the effect you want. When you Click on the left side of the line it'll move right and vice-versa. Now if you want to change direction when you click to something different than + / - 1, simply change the values of the two lines, or create a public variable so you can do it whilst in the inspector. Hope this has helped!
Upvotes: 0