Skip to content

Instantly share code, notes, and snippets.

@tsubaki tsubaki/Simulate.cs

Last active May 4, 2018
Embed
What would you like to do?
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
You can’t perform that action at this time.