How to do Animation to line renderer in Unity C# - c#

Is there any way to add animation to this line renderer? I mean I want to draw a line from Point 1 to point3 the line should move like a progress bar. How to do it in the below script
public class DrawLineRenderer : MonoBehaviour
{
public Transform Point1;
public Transform Point2;
public Transform Point3;
public LineRenderer linerenderer;
public float vertexCount = 12;
public float Point2Ypositio = 2;
// Start is called before the first frame update
void Start()
{
linerenderer.SetWidth(10, 10);
}
// Update is called once per frame
void Update()
{
}
public void buttonPress()
{
Point2.transform.position = new Vector3((Point1.transform.position.x + Point3.transform.position.x)/2, Point2Ypositio, (Point1.transform.position.z + Point3.transform.position.z) /2);
var pointList = new List<Vector3>();
for(float ratio = 0;ratio<=1;ratio+= 1/vertexCount)
{
var tangent1 = Vector3.Lerp(Point1.position, Point2.position, ratio);
var tangent2 = Vector3.Lerp(Point2.position, Point3.position, ratio);
var curve = Vector3.Lerp(tangent1, tangent2, ratio);
pointList.Add(curve);
}
linerenderer.positionCount = pointList.Count;
linerenderer.SetPositions(pointList.ToArray());
}
}

Related

How to check if object is inside terrain area?

I have a plane and when i click on the plane it's spawning objects on the plane area and on the terrain ground.
but i want to do that if the plane or part of it is out of the terrain area that it will disable the spawning part.
This screenshot show the plane above the terrain.
and this screenshot where the plane is out of the terrain area but i can still click on the plane and spawn objects.
This is the spawn objects script :
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public class SpawnObjects : MonoBehaviour
{
public GameObject prefabToSpawn;
public Terrain terrain;
public CustomPlane plane;
public GameObject spawnedTerrainObjectsParent;
public GameObject spawnedPlaneObjectsParent;
public bool go = false;
public int numberOfObjects;
public float duration;
public float yOffset = 0.5f;
public bool isParent = true;
private float terrainWidth;
private float terrainLength;
private float xTerrainPos;
private float zTerrainPos;
private float planeWidth;
private float planeLength;
private float xPlanePos;
private float zPlanePos;
private float yValTerrain;
private float yValPlane;
private float randXTerrain;
private float randZTerrain;
private float randXPlane;
private float randZPlane;
private GameObject cube;
private Collider terrainCollider;
void Awake()
{
if (terrain != null)
{
//Get terrain size
terrainWidth = terrain.terrainData.size.x;
terrainLength = terrain.terrainData.size.z;
//Get terrain position
xTerrainPos = terrain.transform.position.x;
zTerrainPos = terrain.transform.position.z;
terrainCollider = terrain.GetComponent<Collider>();
}
if (plane != null)
{
planeWidth = plane.width;
planeLength = plane.length;
xPlanePos = plane.transform.position.x;
zPlanePos = plane.transform.position.z;
}
if (isParent)
{
if(spawnedTerrainObjectsParent == null)
{
spawnedTerrainObjectsParent = GameObject.Find("Spawned Terrain Parent");
}
if(spawnedPlaneObjectsParent == null)
{
spawnedPlaneObjectsParent = GameObject.Find("Spawned Plane Parent");
}
}
Camera.main.transform.position =
new Vector3(plane.GetComponent<Renderer>().bounds.center.x, 635,
plane.GetComponent<Renderer>().bounds.center.z);
if (go)
{
StartCoroutine(Generate());
}
}
IEnumerator Generate()
{
//Generate the Prefab on the generated position
for (int i = 0; i < numberOfObjects; i++)
{
if (terrain != null)
{
//Generate random x,z,y position on the terrain
randXTerrain = UnityEngine.Random.Range(xTerrainPos, xTerrainPos + terrainWidth);
randZTerrain = UnityEngine.Random.Range(zTerrainPos, zTerrainPos + terrainLength);
yValTerrain = Terrain.activeTerrain.SampleHeight(new Vector3(randXTerrain, 0, randZTerrain));
yValTerrain = yValTerrain + yOffset;
GameObject objInstanceTerrain = (GameObject)Instantiate(prefabToSpawn,
new Vector3(randXTerrain, yValTerrain, randZTerrain), Quaternion.identity);
objInstanceTerrain.name = "Terrain Spawned";
if (isParent)
{
objInstanceTerrain.transform.parent = spawnedTerrainObjectsParent.transform;
}
}
if (plane != null)
{
randXPlane = UnityEngine.Random.Range(xPlanePos, xPlanePos + planeWidth);
randZPlane = UnityEngine.Random.Range(zPlanePos, zPlanePos + planeLength);
yValPlane = 0;
yValPlane = yValPlane + yOffset;
GameObject objInstancePlane = (GameObject)Instantiate(prefabToSpawn,
new Vector3(randXPlane, yValPlane, randZPlane), Quaternion.identity);
objInstancePlane.name = "Plane Spawned";
if (isParent)
{
objInstancePlane.transform.parent = spawnedPlaneObjectsParent.transform;
}
}
if (duration > 0)
{
yield return new WaitForSeconds(duration);
}
}
}
private void Update()
{
SpawnThroughPlane();
}
public void SpawnThroughPlane()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (plane.GetComponent<MeshCollider>().Raycast(ray, out hit, Mathf.Infinity))
{
cube = Instantiate(prefabToSpawn);
cube.transform.position = hit.point;
float heightFromTerrain = Terrain.activeTerrain.SampleHeight(hit.point);
var posy = hit.point.y;
posy -= heightFromTerrain;
var newpos = new Vector3(hit.point.x, hit.point.y - posy, hit.point.z);
Instantiate(prefabToSpawn, newpos, Quaternion.identity);
}
}
}
}

How change cave position of this line renderer

I am using the following code to draw a curved dotted line using a line renderer(Copied from the net). It's working but the curve is forming downward like a boat. I want to draw the curve in the opposite direction. I tried adjusting the values but no luck. can anyone can please say how to do this with this code? or can suggest me new set of code
NB- I only have very basic knowledge in programming.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DrawLineRenderer : MonoBehaviour
{
public Transform Point1;
public Transform Point2;
public Transform Point3;
public LineRenderer linerenderer;
public float vertexCount = 12;
public float Point2Ypositio = 2;
// Start is called before the first frame update
void Start()
{
linerenderer.SetWidth(10, 10);
}
public void buttonPress()
{
Point2.transform.position = new Vector3((Point1.transform.position.x + Point3.transform.position.x)/2, Point2Ypositio, (Point1.transform.position.z + Point3.transform.position.z) *2);
var pointList = new List<Vector3>();
for(float ratio = 0;ratio<=1;ratio+= 1/vertexCount)
{
var tangent1 = Vector3.Lerp(Point1.position, Point2.position, ratio);
var tangent2 = Vector3.Lerp(Point2.position, Point3.position, ratio);
var curve = Vector3.Lerp(tangent1, tangent2, ratio);
pointList.Add(curve);
}
linerenderer.positionCount = pointList.Count;
linerenderer.SetPositions(pointList.ToArray());
}
}
Set Point2Ypositio =600
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DrawLineRenderer : MonoBehaviour
{
public Transform Point1;
public Transform Point2;
public Transform Point3;
public LineRenderer linerenderer;
public float vertexCount = 12;
public float Point2Ypositio = 600;
// Start is called before the first frame update
void Start()
{
linerenderer.SetWidth(10, 10);
}
public void buttonPress()
{
Point2.transform.position = new Vector3((Point1.transform.position.x + Point3.transform.position.x)/2, Point2Ypositio, (Point1.transform.position.z + Point3.transform.position.z) *2);
var pointList = new List<Vector3>();
for(float ratio = 0;ratio<=1;ratio+= 1/vertexCount)
{
var tangent1 = Vector3.Lerp(Point1.position, Point2.position, ratio);
var tangent2 = Vector3.Lerp(Point2.position, Point3.position, ratio);
var curve = Vector3.Lerp(tangent1, tangent2, ratio);
pointList.Add(curve);
}
linerenderer.positionCount = pointList.Count;
linerenderer.SetPositions(pointList.ToArray());
}
}

How do I Instantiate a line renderer and give it positions for its points

I apologize for the block of code below but I am not sure where the issue is. I am trying to get a laser to appear off screen and attempt to hit the player. I have no idea why this code does nothing. It is most likey just a stupid mistake I have made.
`
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Lasers : MonoBehaviour
{
private LineRenderer lr;
public bool Above = true;
public bool Below = false;
public bool Left = false;
public bool Right = false;
public Transform LaserStartPoint;
public Transform LaserEndPoint;
public Transform Player;
public float LaserWidth = 0.75f;
public float LaserLength = 19f;
public float LaserDuration = 0.5f;
public float LaserFadeDuration = 0.5f;
public GameObject Laser;
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
ShootLaser();
}
}
void ShootLaser()
{
if(Above)
{
LaserStartPoint.position = new Vector3(Random.Range(-10,10), 6, -1);
}
if(Below)
{
LaserStartPoint.position = new Vector3(Random.Range(-10,10), -6, -1);
}
if(Left)
{
LaserStartPoint.position = new Vector3(-10, Random.Range(-6,6), -1);
}
if(Right)
{
LaserStartPoint.position = new Vector3(10, Random.Range(-6,6), -1);
}
Instantiate(Laser, LaserStartPoint.position, Quaternion.identity);
lr = Laser.GetComponent<LineRenderer>();
lr.startWidth = LaserWidth;
lr.endWidth = LaserWidth;
lr.positionCount = 2;
Vector3 dir = Player.position - LaserStartPoint.position;
LaserEndPoint.position = LaserStartPoint.position + dir.normalized * LaserLength;
lr.SetPosition(0, LaserStartPoint.position);
lr.SetPosition(1, LaserEndPoint.position);
Invoke("FadeLaser", LaserDuration);
}
void FadeLaser()
{
lr.startColor = Color.Lerp(lr.startColor, Color.clear, LaserFadeDuration);
lr.endColor = Color.Lerp(lr.endColor, Color.clear, LaserFadeDuration);
Laser.SetActive(false);
}
}
`
I have looked in the Hierarchy and nothing is spawning. None of the values are changing on the Script. I have the script attached to the main camera and it spawns in my LaserLineRenderer prefab.
You are attempting to modify the line renderer component of the prefab. You need to grab the reference of the instantiated object when it is spawned in.
private GameObject instantiatedLazer;
/*In ShootLaser function*/
instantiatedLazer = Instantiate(Laser, LaserStartPoint.position, Quaternion.identity);
lr = instantiatedLazer.GetComponent<LineRenderer>();
/*In FadeLaser function*/
instantiatedLazer.SetActive(false);

Orienting an ellipse in 3D space

I am trying to create an ellipse in 3D space. Ive used
https://www.youtube.com/watch?v=mQKGRoV_jBc
https://www.youtube.com/watch?v=Or3fA-UjnwU&t=390s
https://www.youtube.com/watch?v=lKfqi52PqHk
to create an ellipse. Now the ellipse is constructed via a xAxis and a yAxis. I need to move the middlepoint of the ellipse a given distance in a certain direction and then tilt the hole plane on which the ellipse is constructed at a certain angle.
Now my idea is to take the transform.position of the constructing empty and offset it in the direction needed and at the distance needed. The idea goes then further by simply rotating the constructing empty the given angle. Unfortunelty I have 0 clue how to. Ive provided you with the Ellipse class creating the Ellipse and the EllipseRenderer-script so you have an idea whats going on.
[System.Serializable]
public class Ellipse
{
float xAxis;
float yAxis;
public Ellipse(float xAxis, float yAxis)
{
this.xAxis = xAxis;
this.yAxis = yAxis;
}
public Vector2 Evaluate(float orbitalProgression)
{
float angle = Mathf.Deg2Rad * 360 * orbitalProgression;
float x = Mathf.Sin(angle) * xAxis;
float y = Mathf.Cos(angle) * yAxis;
return new Vector2(x, y);
}
}
,
public class OrbitMotion : MonoBehaviour
{
public Transform orbitingObject;
public Ellipse orbitPath;
[Range(0f,1f)]
public float orbitProgress = 0f;
public float orbitPeriod = 3f;
public bool orbitActive = false;
void Start()
{
if (orbitingObject == null)
{
orbitActive = false;
return;
}
SetOrbitingObjectPosition();
StartCoroutine(AnimateOrbit());
}
void SetOrbitingObjectPosition()
{
Vector2 orbitPos = orbitPath.Evaluate(orbitProgress);
orbitingObject.position = new Vector3(orbitPos.x, 0, orbitPos.y);
}
IEnumerator AnimateOrbit()
{
if (orbitPeriod < 0.1f)
{
orbitPeriod = 0.1f;
}
float orbitspeed = 1 / orbitPeriod;
while (orbitActive)
{
orbitProgress += Time.deltaTime * orbitspeed;
orbitProgress %= 1f;
SetOrbitingObjectPosition();
yield return null;
}
}
}
and
[RequireComponent(typeof(LineRenderer))]
public class EllipseRenderer : MonoBehaviour
{
[Range(3, 36)]
public int segments = 7;
public LineRenderer lr;
public Ellipse ellipse;
private void Awake()
{
lr = GetComponent<LineRenderer>();
CalculateEllipse();
}
void CalculateEllipse()
{
Vector3[] points = new Vector3[segments + 1];
for (int i = 0; i < segments; i++)
{
Vector2 position2D = ellipse.Evaluate((float)i / (float)segments);
points[i] = new Vector3(position2D.x, position2D.y, 0);
}
points[segments] = points[0];
lr.positionCount = segments + 1;
lr.SetPositions(points);
}
public Vector3 CalculatePosition()
{
}
private void OnValidate()
{
CalculateEllipse();
}
}

How can I create a manager script to control all drawn circles at once?

The first script is for drawing the circle:
When I attach this script to a gameobject it's drawing a circle around the object.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[RequireComponent(typeof(LineRenderer))]
public class DrawCircle : MonoBehaviour
{
[Range(0, 50)]
public int segments = 50;
[Range(1, 50)]
public float xradius = 5;
[Range(1, 50)]
public float yradius = 5;
[Range(-10, 10)]
public float height = 0;
public bool changeBothRadius = false;
[Range(0.1f, 2)]
public float lineThickness = 0.1f;
public bool minimumRadius = false;
private LineRenderer line;
void Start()
{
line = gameObject.GetComponent<LineRenderer>();
line.positionCount = segments + 1;
line.useWorldSpace = false;
}
void Update()
{
line.startWidth = lineThickness;
line.endWidth = lineThickness;
CreatePoints();
}
void CreatePoints()
{
float x;
float z;
float angle = 20;
for (int i = 0; i < (segments + 1); i++)
{
x = Mathf.Sin(Mathf.Deg2Rad * angle) * xradius;
z = Mathf.Cos(Mathf.Deg2Rad * angle) * yradius;
line.SetPosition(i, new Vector3(x, height, z));
angle += (360f / segments + 1);
}
}
}
Now I created a manager script that should control all the circles at once:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CirclesManager : MonoBehaviour
{
public GameObject[] objectsToAddCircles;
[Range(0, 50)]
public int segments = 50;
[Range(1, 50)]
public float xradius = 5;
[Range(1, 50)]
public float yradius = 5;
[Range(-10, 10)]
public float height = 0;
public bool changeBothRadius = false;
[Range(0.1f, 2)]
public float lineThickness = 0.1f;
public bool minimumRadius = false;
void Start()
{
for (int i = 0; i < objectsToAddCircles.Length; i++)
{
objectsToAddCircles[i].AddComponent<DrawCircle>();
objectsToAddCircles[i].AddComponent<LineRenderer>();
}
}
void Update()
{
for (int i = 0; i < objectsToAddCircles.Length; i++)
{
var lr = objectsToAddCircles[i].GetComponent<LineRenderer>();
lr.startWidth = lineThickness;
lr.endWidth = lineThickness;
var dc = objectsToAddCircles[i].GetComponent<DrawCircle>();
dc.segments = segments;
dc.xradius = xradius;
dc.yradius = yradius;
dc.height = height;
dc.changeBothRadius = changeBothRadius;
dc.minimumRadius = minimumRadius;
}
}
}
So now each object have the LineRenderer component and the DrawCircle script and now the CirclesManager script is working on all objects fine but if I try to change individual object settings it will not change. For example I can change the xrdaius or yradius sliders in the manager script but if I try to change them in a specific object the sliders won't move will not change.
Can't figure out why the manager script is working but not each individual object with the script and LineRenderer.
In CirclesManager class in Update you have these lines:
dc.xradius = xradius;
dc.yradius = yradius;
No matter where and how you change individual DrawCircle instance radius, these lines would always overwrite those values.
I don`t know what kind of behaviour you want to archive but you can create a bool array so you can manually set which circles would be driven by CirclesManager and which circles would use their own values:
// you can change it in the inspector which is handy
// if i'th value of this array is false
// then i'th CircleDrawer GameObject in objectsToAddCircles array
// won't be affected by this manager
public bool changableCircle[];
void Start() {
// your code
changableCircle = new bool[objectsToAddCircles.Length];
}
void Update() {
for(...) {
// values which are always overwritten by manager
if(changableCircle[i]) {
// values which you don't want to be changed by this manager
}
}
}

Categories