I have a 2d box, and within it, a sphere. When the ball hit’s either of the right or left wall, I would like to limit it’s bounce angles such, that it isn’t possible for it to bounce in too horizontal angles.
Unfortunately, the whole unity angle quaternion thing confuses me. As far as I’m aware, I could even solve the whole thing by adjusting the velocity.
Anyways, tips how to go about solving this?
An interesting problem. Here’s one solution that, as you suggested, changes the velocity at the point of impact. Notes below…
using UnityEngine;
public class Bounce : MonoBehaviour
{
[SerializeField] Vector3 velocity = new Vector3(1, 0, 0);
[SerializeField] float ballSpeed = 5;
void Update()
{
transform.Translate(ballSpeed * Time.deltaTime * velocity, Space.World);
}
Vector3 newVelocity()
{
Vector3 newVector3;
if (Mathf.Abs(Mathf.Atan(velocity.y / velocity.x)) < Mathf.PI / 6)
{
float newY = Mathf.Tan(Mathf.PI / 6);
newVector3 = new Vector3(1, newY, 0).normalized;
newVector3 *= velocity.magnitude;
newVector3.x *= Mathf.Sign(velocity.x);
newVector3.y *= Mathf.Sign(velocity.y);
}
else
{
newVector3 = velocity;
}
return newVector3;
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Walls"))
{
velocity = newVelocity();
velocity = Vector3.Reflect(velocity, collision.GetContact(0).normal);
}
}
}
I’m moving the sphere in the update routine, using the Vector3 called velocity. Replace that as required (possible even using RigidBody.velocity). When the sphere hits a wall (tag of “Walls”), it checks the angle of the incoming velocity and makes sure it’s at least 30 degrees (pi/6 in radians). I then jiggle the new vector to have the same magnitude and signs as the original one. I then use Vector3.Reflect to bounce off the wall.
I tested it using approach angles nearly horizontal going both left and right and it seems to be OK. Do ask if you have any questions…
If the ball is getting stuck to the wall, go to Project Settings > Physics and reduce the Bounce Threshold. Not too low though, because you might introduce unwanted jitter.