I have a game where the player score while getting next to an object. I want to create a line that shoots from the player to the enemy as the player has entered that range.
It seems like Distance Joint 2D does something SIMILAR to what I want, but not quite.
I don’t see a clear way to do it, but I’ll certainly hack at more of it tonight.
I made a beautiful picture to further explain what I’m asking, 'cause I feel like I did a poor job. I want to use this as feedback to let the player know they’ve scored.
Here is a bit of example code. To test it
- Start a new scene
- Create a Quad and set the x scale to the width of the line you want.
- Attach the script below to the Quad
- Crate two game object that are no more that ‘breakDistance’ apart (default 5 units).
- Drag and drop the two game objects onto the ‘start’ and ‘end’ variables.
- Run the app and hit the space bar to connect the line.
- Move one of the game objects so they are more than ‘breakDistance’ apart to break the line.
using UnityEngine;
using System.Collections;
public class LinePulse : MonoBehaviour {
public float pulseTime = 1.0f;
public float breakDistance = 5.0f;
public Transform start;
public Transform end;
private bool pulsing = false;;
void Start() {
renderer.enabled = false;
}
void Update () {
if (Input.GetKeyDown(KeyCode.Space)) {
StartCoroutine(Pulse(pulseTime));
}
}
IEnumerator Pulse(float time) {
if (pulsing) yield break;
pulsing = true;
renderer.enabled = true;
Vector3 scale = transform.localScale;
bool broken = false;
float timer = 0.0f;
while (timer <= 1.0f) {
Vector3 dir = end.position - start.position;
float dist = dir.magnitude;
transform.rotation = Quaternion.FromToRotation (Vector3.up, dir);
float yScale = Mathf.PingPong(timer * 2.0f, 1.0f);
scale.y = yScale * dist;
transform.localScale = scale;
transform.position = Vector3.Lerp (start.position, end.position, timer);
if (!broken && timer > 0.5f && dist > breakDistance)
broken = true;
if (timer < 0.5 || broken)
timer += Time.deltaTime / time;
yield return null;
}
pulsing = false;
renderer.enabled = false;
}
}
For your app, you’ll likely have to set things up a bit differently, but this gives you some sample code that solves the line connecting and breaking.