Add Force at angle

how to add force at an angle.Suppose a ball is falling under effect of gravity, then it should bounce back at an angle.

How to code above sentences.

There are many ways to do it, but theoretically this is the idea, assuming you want to specify the angle yourself:

using UnityEngine;

public class BouncingBall : MonoBehaviour
{
    /**
     * <summary>
     * The bouncing force.
     * </summary>
     * <remarks>
     * Unit: Newton-seconds.
     * </remarks>
     */
    public float bounceForce = 5f;

    /**
     * <summary>
     * The angle at which to apply the bouncing force.
     * </summary>
     * <remarks>
     * Unit: degrees.
     * </remarks>
     */
    public float bounceAngle = 45f;

    /*
     * About when to apply the bouncing computation, it depends on the
     * game mechanic you are trying to implement. If anytime there is
     * a collision detected with your ball you want it to bounce, you
     * can technically put the code in this collision callback. There
     * are better, more complex approaches, but this will give you a
     * good start.
     */

    private void OnCollisionEnter2D(Collision2D collision)
    {
        // Converting the specified angle to radians.
        float angleInRadians = bounceAngle * Mathf.Deg2Rad;

        // Calculating the direction vector from the angle.
        Vector2 forceDirection = new Vector2(
            x: Mathf.Cos(angleInRadians),
            y: Mathf.Sin(angleInRadians)
        );

        /*
         * Fetching the rigidbody. Should be done only once outside of this
         * method but this is just to illustrate the idea.
         */
        Rigidbody2D rb = GetComponent<Rigidbody2D>();

        // Applying the force in the specified direction.
        rb.AddForce(forceDirection * bounceForce, ForceMode2D.Impulse);
    }
}

it worked only once when collision happens. I want the ball to be bounce back at an angle whenever collision happens. The above code bounce the ball only once at angle of 45.
kindly help me to bounce the ball whenever collision

This code is written in the OnCollisionEnter callback meaning that every time a new collision is detected, it will be called. If the collision is not new, you need to call OnCollisionStay, but if you call the code from OnCollisionEnter then bouncing off should remove the collisions so, I honestly don’t see the problem with the code I gave you. Maybe you could explain a little more what your problem is?

are you available on Linkedn or Discord

Why? :sweat_smile:

The whole point of Unity’s Discussions is to share with other people so that they can see the things you struggled with here and then learn from you.

Feel free to explain your problem and me or other people will join the conversation to help you.

If the ball is a rigidbody then you can add a physics material to it with a high bounce setting.

1 Like

Because I am not able share screenshot and video of the problem I am facing.

It is bouncing at 90 degree. Not an 45 or 60 degree.

Id ask why not? youtube offers private listings so only those with link so it doesnt show on searches on youtube, windows has built in capture tools… Id imagine mac does too, only one maybe doesnt is linux but i bet someones made one


Ball Bounced at an angle of 45


Ball bounced at an angle of 90 degree

I want ball to be bounced at an angle of 45 degree when it makes collision.
Th ball bounced at 45 degree only once after that it is bouncing at 90 degree.

kindly help me.

Alright then maybe try this approach:

using UnityEngine;

public class BouncingBall : MonoBehaviour
{
    // Multiplier to control bounce intensity (1 = original velocity).
    public float bounceForce = 1f;

    // Bouncing angle adjustment in degrees.
    public float angleAdjustment = 0f;

    private void OnCollisionEnter2D(Collision2D collision)
    {
        Rigidbody2D rb = GetComponent<Rigidbody2D>();

        /*
         * Calculating the reflection direction based on the current
         * velocity and collision normal
         */
        Vector2 incomingVelocity = rb.velocity;
        Vector2 normal = collision.contacts[0].normal;
        Vector2 bounceDirection = Vector2.Reflect(incomingVelocity.normalized, normal);

        // Applying the angle adjustment to the bounce direction.
        float angleInRadians = angleAdjustment * Mathf.Deg2Rad;
        float cos = Mathf.Cos(angleInRadians);
        float sin = Mathf.Sin(angleInRadians);

        Vector2 adjustedBounceDirection = new Vector2(
            bounceDirection.x * cos - bounceDirection.y * sin,
            bounceDirection.x * sin + bounceDirection.y * cos
        );

        // Applying the adjusted direction with the bounce force multiplier.
        rb.velocity = adjustedBounceDirection * (incomingVelocity.magnitude * bounceForce);
    }
}

This solution is a more complex approach, at least a theoretical lead towards it, you are going to have to refine it to your needs.

The idea now is to reflect the velocity vector and to apply an angle adjustment to the reflection.

I made the computations as simple as possible but you can optimize it and also you shouldn’t update the velocity of a rigidbody the way I proposed, but try to understand what is happening first (at least that would be my advice) and then move on to optimize it once you are familiar with the math involved, and the physics I guess.

Another alternative proposed by @zulo3d, if you are using a Dynamic Rigidbody, is to use Physics Materials and tweek the bouncing property, maybe you should look into it?

I suspect that you’re probably setting the velocity directly when moving the ball. Instead you can move the ball like this:

void FixedUpdate()
{
	rb.AddForce(Vector2.right*Input.GetAxis("Horizontal")); // move the ball left and right
}

void OnCollisionEnter2D(Collision2D c)
{
	rb.AddForce(new Vector2(4,10), ForceMode2D.Impulse); // add some horizontal and upwards force everytime we land
}

Your example is essentially correct however it’s important to note that the callback doesn’t occur before the collision is going to happen, it’s done after the collision has occurred and the collision response has been applied i.e. velocities have already changed and likely the current body velocity is moving away from the surface.

You should use the historic relative velocity:

Also to note that the position of the body isn’t guaranteed to be at the contact point either as it’s likely bounced away from the surface.

1 Like

Indeed you are right, than you for pointing it out.

Personally, I would have opted for a system with a custom collision detection based on sweep queries, using Kinematic Actors, and then when it detects a collision I would make my own numerical integration to compute my reflected velocity, before updating the position of the Rigidbody prior to the physics simulation.

I thought this is a little bit too much for the person that asked the question to implement on their own, so that’s why I proposed using the OnCollision callbacks, for starters.

But indeed they are always “late” and not really suited to implement game mechanics, or maybe I’m wrong? :slightly_smiling_face:

1 Like

I agree with everything you just said and understand why you simplified it. :slight_smile:

Just thought I’d add the extra detail for others reading it too.

Not late, just notifying that it’s happened already.

1 Like

this code is not working

this code has been working only once when it make collision with player object.
when the ball touched the boundary then there is no space available for bouncing ball back at angle.
I need your help. when the ball touched boundary then it should bonce back at angle.