I want to make a bouncing ball game and I have to control the direction of where the (continuously bouncing) ball is travelling. The problem is that by adding force the ball picks up more and more speed the further I try to control it cuz the friction on the rigidbody must be zero and I am using Rigidbody().AddForce(). How do I move it around without adding excessive force? How do I make the bouncing ball bounce (move) in the direction that I want? I don't want to use animations, the game will be based on various physics events.

Here is my code:

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

public class Player : MonoBehaviour{
public Color[] colors;
private Renderer renderer;

private void Awake(){
    renderer = this.GetComponent<Renderer>();

    InvokeRepeating("ChangeColor", 0, 3f);
}

private void FixedUpdate()
{
    MoveBall();
}

void ChangeColor(){
    renderer.material.color = colors[Random.Range(0, colors.Length)];
}
void MoveBall(){
    Debug.Log(GetComponent<Rigidbody>().velocity.magnitude);

        if (Input.GetKey("w"))
        {
            GetComponent<Rigidbody>().AddForce(new Vector3(0, 0, 1) * (30f - (GetComponent<Rigidbody>().velocity.magnitude*9)));
        }
        if (Input.GetKey("s"))
        {
            GetComponent<Rigidbody>().AddForce(new Vector3(0, 0, -1) * (30f - (GetComponent<Rigidbody>().velocity.magnitude*9)));
        }
        if (Input.GetKey("a"))
        {
            GetComponent<Rigidbody>().AddForce(new Vector3(-1, 0, 0) * (30f - (GetComponent<Rigidbody>().velocity.magnitude*9)));
        }
        if (Input.GetKey("d"))
        {
            GetComponent<Rigidbody>().AddForce(new Vector3(1, 0, 0) * (30f - (GetComponent<Rigidbody>().velocity.magnitude*9)));
        }

}

}

1 Answers

1
ryeMoss On Best Solutions

You can either set a limit on the velocity so that it doesn't accelerate past your desired max:

rigidbody.velocity = Vector3.ClampMagnitude(rigidbody.velocity, maxSpeed);

Or, if it doesn't break your desired physics method, you can modify the velocity of the object directly, and eliminate any acceleration using:

rigidbody.velocity = new Vector3();