- Home /
Object move and bounce off walls infinitely
Hello,
I have a simple object in a square 3D room with walls.
I want to have an object move infinitely inside of it, and when it hits a wall I would like the object to bounce off like in the image.
This is my current script that doesn't work correctly...
[SerializeField] GameObject DirectionObject;
private void Update()
{
transform.position += DirectionObject.transform.forward * Time.deltaTime * 2f;
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Floor"))
return;
DirectionObject.transform.rotation =
Quaternion.Euler(DirectionObject.transform.localRotation.eulerAngles.x,
DirectionObject.transform.localRotation.eulerAngles.y + 90,
DirectionObject.transform.localRotation.eulerAngles.z);
}
Answer by maormenashe · Feb 13, 2020 at 05:24 PM
I see you're using transform to move the ball, i assume you have rigidbody on the ball since you're using "OnCollisionEnter" event function. Why do you move the player using the transform? is there any particular reason?
I suggest you use force, rather than changing the transform. For infinite bounce you need to add both the ball and the walls a physics material with bounce value of 1.
I don't know if you'll get the exact results you're looking for as in the image, but it all depends on the physics and the applied force on the ball.
Hope this helps.
ok, and apply force in which direction? that is how i dont know how to calculate. :(
What's your goal exactly? You just want the ball to move in the path presented in the image? Or you want the ball to have specific physics?
Unity will calculate the collision bounce for you, you don't need to do that yourself (unless, as the answerer mentions, when you want specific non-typical-physics functionality).
this ball is an enemy that when the player touches he loses health. let's say there are multiple of these. i want them to bounce off the walls, each other and the player. if i make them bouncy they get out of control.
Your answer
Follow this Question
Related Questions
Why is gameobject rotating by 90 degrees only once? 1 Answer
Trying to make object bounce off walls - gets stuck! 1 Answer
Issues with Bullet Ricochet 1 Answer
Disable horizontal movement (2D) 0 Answers
Object Bouncing of Others 2 Answers