Skip to content

Instantly share code, notes, and snippets.

@tsubaki
Last active May 4, 2018 10:56
Show Gist options
  • Save tsubaki/4c4b95a10c576c7a0034eafb7efbca0f to your computer and use it in GitHub Desktop.
Save tsubaki/4c4b95a10c576c7a0034eafb7efbca0f to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(LineRenderer))]
public class Simulate : MonoBehaviour
{
[SerializeField] Transform target;
[SerializeField] LineRenderer line;
[SerializeField][Range(0.001f, 10)] float maxTime = 5;
[SerializeField] [Range(0, 12)] int power = 5;
private List<Vector3> positions = new List<Vector3>();
private Vector3 presposition = Vector3.zero;
private int prePower = -1;
private Transform startPosition;
private void Start()
{
startPosition = transform;
}
void Update ()
{
Physics.autoSimulation = false;
if (presposition == transform.position && power == prePower)
return;
presposition = transform.position;
prePower = power;
positions.Clear();
ResetRigidbody();
AddForce();
ProgressSimulate();
line.positionCount = positions.Count;
line.SetPositions(positions.ToArray());
}
private void OnDisable()
{
Physics.autoSimulation = true;
ResetRigidbody();
}
private void AddForce()
{
var rig = target.GetComponent<Rigidbody>();
rig.AddForce(new Vector3(1, 1, 0) * power, ForceMode.Impulse);
}
private void ProgressSimulate()
{
float time = 0;
float deltaTime = Time.fixedDeltaTime;
while (time < maxTime)
{
Physics.Simulate(deltaTime);
time += deltaTime;
positions.Add(target.position);
}
}
void ResetRigidbody()
{
target.position = startPosition.position;
target.rotation = startPosition.rotation;
var rig = target.GetComponent<Rigidbody>();
rig.velocity = Vector3.zero;
rig.angularVelocity = Vector3.zero;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment