Skip to content

Instantly share code, notes, and snippets.

@NotYannis
Created January 13, 2018 17:37
Show Gist options
  • Save NotYannis/65a6ad80c0988a4520109edcc147aace to your computer and use it in GitHub Desktop.
Save NotYannis/65a6ad80c0988a4520109edcc147aace to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CollectiblePieceScript : MonoBehaviour {
Vector3 target;
TrailRenderer trail;
Rigidbody2D rb;
Transform baseParent;
SpriteRenderer sprite;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
trail = GetComponent<TrailRenderer>();
sprite = GetComponent<SpriteRenderer>();
trail.enabled = false;
baseParent = this.transform.parent;
}
// Use this for initialization
void Start()
{
target = GameObject.Find("ScoreTrigger").transform.position;
}
public void Explode()
{
rb.WakeUp();
Vector2 explodeForce = Vector2.left + Vector2.up;
explodeForce.Normalize();
explodeForce = transform.TransformDirection(explodeForce);
explodeForce += new Vector2(Random.Range(-0.5f, 0.5f), Random.Range(-0.5f, 0.5f));
rb.AddForce(explodeForce * 1000.0f, ForceMode2D.Impulse);
trail.enabled = true;
sprite.enabled = true;
}
public void Reset()
{
trail.enabled = false;
sprite.enabled = false;
rb.Sleep();
this.transform.parent = baseParent;
this.transform.localPosition = Vector3.zero;
this.GetComponent<CollectiblePieceScript>().enabled = false;
}
// Update is called once per frame
void Update()
{
MoveToTarget();
}
void MoveToTarget()
{
Vector2 force = target - transform.position;
float distance = force.magnitude;
force.Normalize();
float strength = distance * distance * 10.0f;
strength = Mathf.Clamp(strength, 1.0f, 800000.0f);
force *= strength;
force *= 0.5f;
rb.AddForce(force * Time.deltaTime);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment