- Home /
How to turn around the ball direction immediately and keep the ball speed constant?
Hi, I am beginner of Unity I want to ask some question. As you can see in the picture, I want to move a ball toward blue block and when it touch the blue block, I want to make the ball direction toward re block immediately keeping the ball speed constant.
How to turn around the ball direction immediately and keep the ball speed constant? Is there any good algorithm?
I was about to use velocity in rigidbody component but it's hard for me to make it. Please help
you should setup a rigidbody. then attach a script to the ball. in the script you would change the rigidbody.velocity. i would recommend turning the cubes so that there forward direction is the direction you want your ball to go when it collides. Then use OncollisionEnter() to detect a collition and change the ball's velocity to match the transform.forward of the cube .
Answer by GreenSerpent · Nov 26, 2018 at 02:59 AM
Well, assuming that the ball's forward direction is facing the side with the blue cube, I think this is how you would do it. You would need a rigidbody with gravity enabled on the sphere. Then you would need to add a script to the sphere with the following code:
public float raycastDist = 1;
public float speed = 1;
void FixedUpdate () {
if (Physics.Raycast(transform.position, -Vector3.up, raycastDist)) {
transform.forward = -transform.right;
}
gameObject.GetComponent<Rigidbody>().velocity = new Vector3(0, gameObject.GetComponent<Rigidbody>().velocity.y, speed);
}
In Unity, you would need to set raycastDist to something slightly more than half of the size of the sphere. So, if your sphere was 1 by 1 by 1, then you would set raycastDist to 0.51. You would set the speed variable to whatever you think works well in your game.