Hey there,
I am trying to implement a pushback effect as seen here: https://youtu.be/v2uOGQegj2c?t=270
When a projectile hits a player, the player is pushed back in a direction relative to the hit collision position.
I have tried this snippet of code:
private void OnCollisionEnter(Collision other)
{
if (other.gameObject.name.Contains("Fireball"))
{
Debug.Log("Fireball collided with player");
directionRaw = transform.position - other.transform.position;
directionRaw.Normalize();
//rb is the rigidbody of the player
rb.AddForce(directionRaw * force * Time.fixedDeltaTime, ForceMode.Impulse);
}
}
Also, I have tried this example:
private void OnCollisionEnter(Collision other)
{
if (other.gameObject.name.Contains("Fireball"))
{
Debug.Log("Fireball collided with player");
directionRaw = transform.position - other.transform.position;
direction.Normalize();
rb.velocity = Vector3.Lerp(rb.velocity, directionRaw, force);
}
However, none of them seem to work as intended - either not pushing back the player at all or just by a small distance, barely noticeable. I tried to set the force to a great number but the results are the same - not working.
Another thing I tried is to set the AddForce or Velocity change in a FixedUpdate like so:
private void FixedUpdate()
{
if (hit && pushbackTime > 0)
{
//The example with velocity change
rb.velocity = Vector3.Lerp(rb.velocity, directionRaw, force * Time.fixedDeltaTime);
//The example with AddForce
rb.AddForce(directionRaw * force * Time.fixedDeltaTime, ForceMode.Impulse);
}
else if (pushbackTime == 0)
{
hit = false;
}
}
private void OnCollisionEnter(Collision other)
{
if (other.gameObject.name.Contains("Fireball"))
{
Debug.Log("Fireball collided with player");
directionRaw = transform.position - other.transform.position;
directionRaw.Normalize();
pushbackTime = 0.5f;
hit = true;
}
}
Please keep in mind that the incrementing of pushbackTime is set in another function, which is working perfectly fine - thus not necessary to include it in here.
The last option I listed gives me very inconsistent pushbacks. As the game is 3D, I always set the Y axis of the directionRaw to be around 30-45 as I want the player to be pushed back and sort of imitate a jump back.
All in all, none of the techniques are working or working adequately.
Any help with the pushback effect will be much appreciated.
↧