Line Renderer Positions Not Updating
I'm working on a code where if my player attacks and there is a hook object, the player will then transition into state where they're swinging on the hook from a rope. I'm using a distance joint and a line renderer to draw the rope. Everything works perfectly except that once the line is drawn, the position of the line does not update when the player moves. The line.SetPosition gets the point of the hook when it initially connects, but won't update after that. I need it to update with the player's transform so it looks like the player is swinging on the rope. hookPos is the player, hook is the hook object that the overlap circle detects. Any ideas on how I can get this to update each frame?
Here's the code:
void Update()
{
if (Time.time >= nextAttackTime)
{
if (Input.GetButtonDown("Attack"))
{
Attack();
nextAttackTime = Time.time + 1f / attackRate;
Collider2D[] hookGrapple = Physics2D.OverlapCircleAll(HorizontalAttackPoint.position, hookSize, hookLayers);
if (isFacingUp == false && isFacingDown == false)
{
hookGrapple = Physics2D.OverlapCircleAll(HorizontalAttackPoint.position, hookSize, hookLayers);
}
foreach(Collider2D hook in hookGrapple)
{
joint.enabled = true;
line.enabled = true;
joint.connectedAnchor = hook.transform.position;
line.positionCount = 2;
line.SetPosition(0, hookPos.transform.position);
line.SetPosition(1, hook.transform.position);
}
}
}
Answer by Baronguard · Jul 23, 2021 at 10:10 PM
To me it looks as though your code that updates the line point position to be on the player's current position is not being run each update, and rather only runs under the "if (Input.GetButtonDown("Attack"))" if statement, since the position of its closing parentheses is on line 30. A quick fix would be to put a 2nd line.SetPosition(0, hookPos.transform.position); on the outside of the if statement but still inside your Update() function. I imagine you will need more iteration from there to make it look like how you want but I think this should solve your current problem.
Your answer
Follow this Question
Related Questions
How to Instantiate objects at random positions with a certain distance between each other? 2d 0 Answers
Getting the correct angle for OverLapBoxAll 1 Answer
Calculate distance and find nearest object 1 Answer
Checking for Raycast distances not working as expected. 0 Answers
Feild of view only wokring in specific areas of the scene 0 Answers