Question by
guitarmaniac · Oct 02, 2018 at 08:56 PM ·
physics2dupdate functioncalculationinconsistent
Calculation errors?
I am coding a spring-mass dampener system in Unity and I am having trouble keeping a consistent oscillation. When the damping value is 0, the spring should oscillate indefinitely (while maintaining the same amplitude). All the formulas I am using are checked by a professor, so no issue there. But my spring keeps overshooting or undershooting the amplitude if I leave it running for a while. How can I fix this?
screen.png
(184.2 kB)
Comment
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpringScript : $$anonymous$$onoBehaviour
{
private Rigidbody2D gObject;
private Vector2 appliedForce, displacement, staticDisplacement;
private static readonly float GRAVITY = 9.81f;
public float mass, stiffness, damping;
void Start()
{
//default values
stiffness = 40f;
damping = 0.5f;
staticDisplacement = transform.localPosition;
gObject = GetComponent<Rigidbody2D>();
mass = gObject.mass;
}
private void SetStaticDisplacement()
{
staticDisplacement.x = GetWeight().x / stiffness;
staticDisplacement.y = GetWeight().y / stiffness;
}
private void SetDisplacement()
{
SetStaticDisplacement();
displacement.x = staticDisplacement.x - transform.localPosition.x;
displacement.y = staticDisplacement.y - transform.localPosition.y;
}
private Vector2 GetSpringForce()
{
SetDisplacement();
return stiffness * displacement;
}
private Vector2 GetDampingForce()
{
return damping * gObject.velocity;
}
private Vector2 GetAppliedForce()
{
return GetWeight() + GetSpringForce() - GetDampingForce();
}
private Vector2 GetWeight()
{
mass = gObject.mass;
return new Vector2(0, -1 * mass * GRAVITY);
}
// Update is called once per frame
void FixedUpdate()
{
//Debug.Log("Position: " + transform.position);
//Debug.Log("Velocity: " + gObject.velocity);
//Debug.Log("weight: " + GetWeight());
//Debug.Log("SpringForce: " + GetSpringForce());
//Debug.Log("DampingForce: " + GetDampingForce());
//Debug.Log("Applied force: " + GetAppliedForce());
//Debug.Log("Displacement: " + displacement);
//Debug.Log("Static Displacement: " + staticDisplacement);
gObject.AddForce(GetAppliedForce(), Force$$anonymous$$ode2D.Force);
}
}