How to Create Bouncing in real time by scripting

Hello everybody,

I want to create bounce affect by scripting. So what I want is I’m trying to bounce the ball with the cube that player is controlling. But issue is that I’m not getting same result every time when I’m trying to bounce the ball.

What kind of path should I follow to get same bounce distance?

Here is the code maybe it would be helpful somehow:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Bounce: MonoBehaviour
{
    public LayerMask layerMask;
    public float ApplyForce;
    bool canForce;
    Rigidbody rb;
    float a = 2;
    private void Start()
    {
        rb = GetComponent<Rigidbody>(); 
    }
    private void Update()
    {
        Ray ray = new Ray(transform.position,Vector3.down);

        RaycastHit hit;
        a += Time.deltaTime;
        if(Physics.Raycast(ray, out hit, .5f, layerMask) && a > .5f )
        {
            Debug.Log("Hit");   
            canForce = true;
            a = 0;
        }
    }

    private void FixedUpdate()
    {
        if(canForce)
        {
            rb.AddForce(Vector3.up * ApplyForce, ForceMode.VelocityChange);
            canForce = false;
        }
    }
}

I’m not very experienced with code, but you could create a physics material with a bounciness of 1, and apply this to the collider of your object. This may not be what you want, though.

Hi,

First, don’t use raycast, try OnCollisionEnter.
Second, don’t use Physics system(because it’s random in a way), you can do it math.

I think you should use rb.AddForce(Vector3.up * ApplyForce, ForceMode.Impulse);

Because the force has to be applied once, So I think using impulse mode makes sense as that’s what I would do for jumping as well.

First, I’ll repeat what you described because I’m not sure I understood. I believe you want player to hold a cube in hand (I’m picturing this as a VR game) and use the cube as a tool to bounce a ball (which has this Bounce script on it) up into the air each time it comes down, sort of like bouncing a ping-pong ball upward over and over. Is this correct?

If so, I believe @DaVinci_13 and @hamzakhan201021 both have it correct. You want to use OnCollisionEnter() instead of scanning for bounce in any Update() method, and when the callback arrives, ForceMode.Impulse is the correct mode.

Also, if I understood the use case correctly, the player will be moving the cube, which means in addition to bouncing based on its own attributes, the ball will need to receive its force vector from the cube’s velocity. If you use OnCollisionEnter(), you’ll have reference to the cube object, from which you can plug the cube’s velocity into the AddForce method of the ball.