- Home /
Making an object realistically rebound off walls
Hi! I am doing a school project in which I need a sphere to hit the edge of a wall and rebound realistically, similarly to the physics in pong. I'm not sure really how to do this, I've been trying to manipulate what rotation it was before hitting the wall and using it to change how much rotation there should be. It seems like this is not the right approach. Here's a simple drawing of what I'm talking about.
Here's the code I was trying to manipulate to rebound:
private void OnTriggerEnter(Collider other)
{
transform.rotation = Quaternion.Euler(objectRotationVariable, 90, 90);
} //The rotation is done on the x-axis
I can use physics, but I would like to be able to heavily control it through code.
Answer by Ady_M · Jan 04, 2019 at 01:49 AM
If you don't mind moving using a Velocity variable and if you only have those two walls opposite each other then you can use the following code. Replace Z with whatever axis points towards your walls.
public Vector3 myVelocity;
private void Update ()
{
// Move
transform.position += myVelocity * Time.deltaTime;
// Look in the direction it's moving in
transform.rotation = Quaternion.LookRotation (myVelocity);
}
private void OnTriggerEnter (Collider other)
{
myVelocity.z *= -1; // Flip
}
Be aware, though, that triggers are not as precise as regular Colliders. Depending on the speed of the ball, it could be halfway inside the wall before OnTriggerEnter occurs.
Your answer
Follow this Question
Related Questions
Play animation 1 Answer
brick does not detect collision although ball does 2 Answers
Rigidbody.SweepTest - Local or Global axis? 1 Answer