Skip to content

Instantly share code, notes, and snippets.

@reidscarboro
Created January 12, 2019 01:30
Show Gist options
  • Save reidscarboro/934a53333281db067432df7cdc094e33 to your computer and use it in GitHub Desktop.
Save reidscarboro/934a53333281db067432df7cdc094e33 to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TetherExample : MonoBehaviour
{
public Transform anchor;
public Transform player;
public LineRenderer lineRenderer;
private Vector3 anchorVelocity;
private void Update()
{
MoveAnchor();
MovePlayer();
ConstrainPlayer();
DrawLine();
}
private void MovePlayer()
{
if (Input.GetKey(KeyCode.W)) {
player.position += Vector3.up * 0.25f;
}
if (Input.GetKey(KeyCode.A)) {
player.position += Vector3.left * 0.25f;
}
if (Input.GetKey(KeyCode.S)) {
player.position += Vector3.down * 0.25f;
}
if (Input.GetKey(KeyCode.D)) {
player.position += Vector3.right * 0.25f;
}
}
private void MoveAnchor()
{
//move the anchor a random amount
anchorVelocity += new Vector3(Random.Range(-0.01f, 0.01f), Random.Range(-0.01f, 0.01f), 0);
//make sure the anchor's velocity doesn't get too high
if (anchorVelocity.magnitude > 0.2f) {
anchorVelocity = anchorVelocity.normalized * 0.2f;
}
anchor.position += anchorVelocity;
}
private void ConstrainPlayer()
{
float maxDistance = 3;
if (Vector3.Distance(anchor.position, player.position) > maxDistance) {
Vector3 anchorToPlayer = player.position - anchor.position;
anchorToPlayer = anchorToPlayer.normalized * maxDistance;
player.position = anchor.position + anchorToPlayer;
}
}
private void DrawLine()
{
lineRenderer.SetPosition(0, player.position);
lineRenderer.SetPosition(1, anchor.position);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment