r/Unity2D • • 5d ago

Question/Help Help with coding a tether

I am currently working on a 2d game where two players are tied to eachother with a rope, I'd use the build in features like a spring joint, distance joint, etc but the problem is that the current code relies on using kinematic rigidbodies so those won't work. So here i am asking for help of how i would program this, I'd also appriciate places where i can learn more about game code in general because the base google searches sure aint doing it for me :p

Here is code i think might be relevant

In my walk state i have:

private void HandleHorizontalMovement()

{

float targetVelocityX = 0f;

if (Mathf.Abs(Ctx.moveInput.x) >= Ctx.moveStats.moveThreshold)

{

float moveDirection = Mathf.Sign(Ctx.moveInput.x);

targetVelocityX = moveDirection * Ctx.moveStats.maxWalkSpeed;

}

float acceleration = Ctx.moveStats.groundAcceleration;

float deceleration = Ctx.moveStats.groundDeceleration;

Vector2 velocity = Ctx.Velocity;

if (Mathf.Abs(Ctx.moveInput.x) >= Ctx.moveStats.moveThreshold)

{

velocity.x = Mathf.Lerp(velocity.x, targetVelocityX, acceleration * Time.fixedDeltaTime);

}

else

{

velocity.x = Mathf.Lerp(velocity.x, 0, deceleration * Time.fixedDeltaTime);

}

Ctx.Velocity = velocity;

}

Then in the PlayerStateMachine I call this

private void FixedUpdate()

{

CountTimers(Time.fixedDeltaTime);

HandleHeadBumpSlide();

_currentState.UpdateStates();

JumpCheck();

TurnCheck(moveInput);

WallJumpCheck();

ClampVelocity();

Controller.Move(Velocity * Time.fixedDeltaTime);

//reset inputs

jumpWasPressed = false;

jumpWasReleased = false;

dashWasPressed = false;

attackWasPressed = false;

_coyoteJumpEnabled = false;

}

And the movement finnaly gets resolved in a different script

public void Move(Vector2 velocity)

{

bool wasGrounded = isCollidngBelow;

UpdateRaycastCorners();

ResetCollisionState();

CheckCeilingBoxCast(velocity);

float stepOffset = 0f;

ResolveHorizontalMovement(ref velocity, wasGrounded, ref stepOffset);

ResolveVerticalMovement(ref velocity);

rb.MovePosition(rb.position + velocity + Vector2.up * stepOffset);

}

0 Upvotes

5 comments sorted by

View all comments

Show parent comment

0

u/ZeSeagull4626 5d ago

I'd like for the rope to stretch a bit

1

u/QueasyPrior6654 4d ago

The spring plus hard cap setup in the other reply is how I'd do it too. One tweak to that formula: clamp pull with Mathf.Max(0f, pull). If they move toward each other fast while still stretched, the damping term can turn pull negative and push them apart.

Since HandleHorizontalMovement lerps horizontal velocity each tick while walking, a separate rope velocity makes sense. Give it its own decay, especially once the rope goes slack, and zero any part blocked by a collision. Include that rope velocity in relSpeed too, or the damping misses it.