- Home /
How to stop ball bouncing in an upwards direction when hitting a wall
I have a mini golf like game that I'm making and I've created all the tracks on blender and imported then over to unity! now when my ball hits a wall sometimes it bounces off correctly but other times it bounces like normal but also raises on the y axis and basically jumps of the track which i don't want to happen, i want it to stay on the track at all times!
now I've checked the blender models I've imported over and the walls are perfectly vertical so no angle to push the ball upwards.
I've tried constraining the y axis but the ball seems to slow down really fast when hitting the wall after (i think this is because it takes the initial power i put on it and changes it to upward power, hence making it move slower)
ive also tried putting no friction on the walls and messing with the physics material but again no luck!
ive checked the forums and can't find anything so if anyone knows how i could keep the ball on the track at all times i would be very thankful.... i can't understand why the ball wants to move up at all but should stay horizontally with the course!
for any more details please ask
Its a hard one to answer without seeing your code!
You say you have tried constraining the Y axis, how?
Also, a very primitive solution you can do is to change the vector of the ball with every update.
I.e myBall = new Vector3(myBall.X, 1, myBallZ)
Answer by Jix · Aug 06, 2014 at 12:22 AM
On the ball script add this code, just make sure that walls have the tag "Wall"
void OnCollisionEnter(Collision other)
{
//Checking if the collision was with a wall
if(other.gameObject.tag == "Wall")
{
Vector3 vel = rigidbody.velocity;
//Finding out the horizontal direction of the ball after hitting a wall
Vector2 horizontalvector = new Vector2(vel.x, vel.z);
//Normalizing the vector so only the direction remains without the speed
horizontalvector = horizontalvector.normalized;
//Adding the force of the original vector to the horizontal direction
horizontalvector = vel.magnitude * horizontalvector;
//Now since the horizontal vector has the same force of the original velocity
//All that remains is to give the ball the new velocity.
//horizontalvector.x in x axis
//horizontalvector.y in z axis
rigidbody.velocity = new Vector3(horizontalvector.x, 0, horizontalvector.y);
}
}
So every time the ball hits something the force resulted from the collision will be directed to a horizontal direction with the same force.
Thanks for your answers however it doesn't seem to work because when it hits the wall its almost like it uses the horizontal velocity and exchanges part of it to vertical velocity, so when you put the horizontal velocity back in after hitting the wall its much slower (and ofcorse this only sometimes happens so sometimes you get fast bounces other times slow bounces)
it acts as if the wall is a ramp however I've checked loads and its perfectly vertical!
what code do you wish to see?