Hello, I have two draggable game objects linked together using spring joint component. I also have a line renderer that connects them with a line (imma post the code down below) and I need to make the line wavy, like an actual spring would be. Any ideas on how should I go about that? Keep in mind im still kinda a newbie to unity and I dont have good programing skillz lol.
The code:
using UnityEngine;
public class Line : MonoBehaviour
{
public GameObject gameObject1; // Reference to the first GameObject
public GameObject gameObject2; // Reference to the second GameObject
private LineRenderer line; // Line Renderer
// Use this for initialization
void Start()
{
// Add a Line Renderer to the GameObject
line = this.gameObject.AddComponent<LineRenderer>();
// Set the width of the Line Renderer
line.SetWidth(0.05F, 0.05F);
// Set the number of vertex fo the Line Renderer
line.SetVertexCount(2);
}
// Update is called once per frame
void Update()
{
// Check if the GameObjects are not null
if (gameObject1 != null && gameObject2 != null)
{
// Update position of the two vertex of the Line Renderer
line.SetPosition(0, gameObject1.transform.position);
line.SetPosition(1, gameObject2.transform.position);
}
}
}
create new material and set a wavy texture, assign it to your line renderer have the texture mode set to strech. No changes in your code required.
instead of line renderer consisting of 2 points, generate a bunch of points between. You will need to know how to use loops (to iterate over all the points), slerp to get points between 2 endpoints, Vector2D.Perpendicular to get vector perpendicular to spring direction, use Mathf.Sin or Mathf.PingPong to get back and forth movement
instead of line renderer use a sprite renderer with sprite that contains desired amount of curves, stretch it by assigning size property. You will need a little bit of math to calculate sprite position and angle from spring endpoints.
I dunno whether Im doing something wrong but in my case it breaks the Spring Joint 2D component that I have on the draggable objects, same goes for the 2D surface - it collides with the draggables. Is there a way around that? I tried putting them on different layers but that didnt seem to help.
Anything in the physics world you want to move needs a Rigidbody2D, either simulated or in the case of platforms and movable ground and whatnot, untick the simulated boolean.
Then whenever you move anything, always consider this:
With Physics (or Physics2D), never manipulate the Transform directly. If you manipulate the Transform directly, you are bypassing the physics system and you can reasonably expect glitching and missed collisions and other physics mayhem.
Always use the .MovePosition() and .MoveRotation() methods on the Rigidbody (or Rigidbody2D) instance in order to move or rotate things. Doing this keeps the physics system informed about what is going on.