- Home /
How do i make piano key like physics?
So, my game includes a section where the character walks along a giant piano, occupying around 2 keys with each step. My problem is: I need to make the keys react like real piano keys, once the character is on the key it goes down depending on how much force the character fell on them, and then quickly back up after the character leaves the piano key.
I tried using spring joint 2d and coding the spring physics myself with no good results because it will always overshoot the desired position. In my coded solution i could use the rigidbody2D component as kinematic, which is what i desire.
Any idea how i could do this?
Answer by PineTreeDev · Jun 07, 2019 at 03:05 PM
Ok finally got something working with the huge help of a teacher, anyone that followed this question, this works perfectly, if you want any behavior when the a key is pressed add it in OnCollisionEnter2D.
public class PianoTile : MonoBehaviour
{
[SerializeField] private float minSpeed;
[SerializeField] private float maxSpeed;
[SerializeField] private float maxOffset = 9f;
private Collider2D selfCollider;
private Vector3 restPos;
private Collider2D lastCollider;
private float resetTimer;
private void Start()
{
restPos = transform.position;
selfCollider = GetComponent<Collider2D>();
resetTimer = 10000.0f;
}
private void FixedUpdate()
{
if (lastCollider != null)
{
if (!lastCollider.IsTouching(selfCollider))
{
resetTimer = 0.0f;
lastCollider = null;
}
else
{
resetTimer = 0.0f;
}
}
else
{
resetTimer += Time.deltaTime;
if (resetTimer > 1.0f)
{
transform.position = Vector3.Lerp(transform.position, restPos, Time.deltaTime);
}
}
}
protected override void OnCollisionEnter2D(Collision2D other)
{
if (resetTimer < 1.0f) return;
float velocityY = Mathf.Abs(other.relativeVelocity.y);
if (velocityY < minSpeed) return;
float totalOffset = maxOffset * velocityY / maxSpeed;
transform.position = restPos + Vector3.down * totalOffset;
lastCollider = other.collider;
resetTimer = 0.0f;
}
private void OnCollisionStay2D(Collision2D other)
{
lastCollider = other.collider;
}
}
Your answer
Follow this Question
Related Questions
Player getting stuck between grounds 0 Answers
OnCollisonEnter2D. 1 Answer
How to create soil or sand?? 1 Answer
Death Counter dont work when changing scenes 2 Answers
How to check if a 2D player collider is touching the ground/platform? 1 Answer