In my scene there is a player and a ball a few units above the ground. The ball has a rigidbody2D attached with zero gravity.
I built a "cage" with square sprites to simulate the edges.
I would like that after the player has hit the ball, the ball moves with a constant speed (no matter how strong the collision with the player is).
I want to recreate something like this after the collision:
https://www.youtube.com/watch?v=zsdPYFPTdw0
I wrote this code:
{
private Rigidbody2D rb;
private Vector2 lastVelocity;
private ConstantForce2D cf;
private Vector2 direction;
private Vector2 surfaceNormal;
[HideInInspector]
public float speed = 5;
[HideInInspector]
public float setTime = 5;
[HideInInspector]
public float smooth = 6;
private bool timeEnded = false;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
cf = GetComponent<ConstantForce2D>();
}
private void Update()
{
Debug.Log(rb.velocity.magnitude);
if (timeEnded)
rb.velocity = Vector2.Lerp(rb.velocity, Vector2.zero, smooth * Time.deltaTime);
}
private void FixedUpdate()
{
lastVelocity = rb.velocity;
}
private void OnCollisionEnter2D(Collision2D collision)
{
// QUANDO VIENE COLPITO
if (collision.collider.tag == "Player")
{
surfaceNormal = collision.contacts[0].normal;
direction = surfaceNormal.normalized;
//cf.force = direction * speed;
rb.AddForce(cf.force = direction * speed * Time.fixedDeltaTime);
StartCoroutine(StopBall());
}
// QUANDO COLPISCE IL MURO
if (collision.collider.tag == "Wall")
{
Vector2 surfaceNormal = collision.contacts[0].normal;
rb.velocity = Vector2.Reflect(lastVelocity, surfaceNormal);
}
}
IEnumerator StopBall()
{
yield return new WaitForSeconds(setTime);
timeEnded = true;
}
}
I still don't understand why the speed doesn't remain constant, why sometimes it's zero and why it depends on the force with which I hit it.