I have a trampoline in my game (RigidBody2D.velocity is used for tilting), the strength of which can be adjusted in the inspector, and I need to calculate how far the player will fly on the Y coordinate, to display the distance in Gizmos.
This is what a quick Claude query gave me:
public class Trampoline : MonoBehaviour
{
public float trampolineStrength = 10f;
private float gravity = -9.81f; // Assuming standard gravity
void OnDrawGizmos()
{
// Calculate the maximum height the player will reach
float maxHeight = CalculateMaxHeight();
// Display the distance in Gizmos
Gizmos.color = Color.green;
Gizmos.DrawLine(transform.position, transform.position + Vector3.up * maxHeight);
Gizmos.DrawSphere(transform.position + Vector3.up * maxHeight, 0.2f);
}
private float CalculateMaxHeight()
{
// Calculate the initial vertical velocity when the player hits the trampoline
float initialVelocity = trampolineStrength;
// Calculate the maximum height using the formula:
// h = (v^2) / (2 * g)
float maxHeight = (initialVelocity * initialVelocity) / (2 * Mathf.Abs(gravity));
return maxHeight;
}
}
Try it out, probably doesnt work super perfect, but its a good starting point
1 Like
I assumed you were using the physics Material 2D to do your game,In my opinion,i suggest using mathematical calculations to solve the problem. (9.81f is the gravity in Unity,Both Collision’s shape and radius are ignored in my code)
private float height = 0f;
private void OnDrawGizmos()
{
Gizmos.color = Color.green;
Gizmos.DrawLine(transform.position, transform.position + Vector3.up * height);
}
private void OnCollisionEnter2D(Collision2D collision)
{
var v = new Vector2 (0,collision.rigidbody.velocity.y);
var a = 9.81f / collision.rigidbody.mass;
var time = v.y / a;
height = v.y * time - a * Mathf.Pow(time, 2) / 2f;
}
Thank you very much.