- Home /
Object following a path and colliding with other objects with physics.
I have multiple balls and made user give a path to the ball. I have taken the input and put it in an array/list. Now I want my ball to follow that path( which can be done with just simply changing its position every frame) but I also want my ball to collide with other balls and have physics been applied. All my balls are RigidBody2D and with my current code which just changes position the ball go through each other.
I am trying to find out a way to be able to give the ball a velocity and make it follow the path(which I have in an array) & if it collides make it follow simple 2D physics rules.
Answer by x4637x · Dec 20, 2017 at 09:05 AM
I used to have the same problem as yours. What I did for the solution is that I add 2 boolean flags, one call lostControl another call settleDown, to decide should the object, in your case is the ball, be controlled by the predefined path or physical impact force. Make the OnCollisonEnter() to set lostControl = true and OnCollisonExit() to set settleDown = true. Then you could have them in your object's (your moving ball) FixedUpdate() to handle movement differently. For example, if lostControl = true will follow simple 2D physics, otherwise will keep moving in path. You could use settleDown for putting your object back to the path or anything like that.
But how do I make it follow simple 2D physics law, like to move the ball I use. ball.transform.position = points [index];
how do I know how do I change it back to normal physics so that it will apply force on its own.
//"points" is my array of location ball needs to go.$$anonymous$$y game is a Skyview so no gravity.(assume a pool table from sky view.
Use Rigidbody.$$anonymous$$ovePosition() ins$$anonymous$$d of change transform.position directly.
If you want a smooth transition, use Vector2.Lerp() to calculate your moving ball's position for each FixedUpdate.
Upon collision happen, code in OnCollisionEnter2D() will be executed.
You could use Rigidbody2D.AddForce() to apply force on impact, the direction of the force should be easy to get by doing some calculation on your own with the Collision2D.GetContacts.
There is another way to do this, you can calculate the force the moving ball need at the start of each waypoint in your path, and then use something like Vector2.Distance(transform.position, destination) to avoid not-stopping-on-waypoint problem. And then assign some physics material to all the collider your moving ball might collide with, set up the bounciness value. Problem solve.
Your answer
Follow this Question
Related Questions
Checking for collision with 2D objects/sprites 3 Answers
Colliders in a wall jut out 0 Answers
Question about Scripting a slingshot mechanic 0 Answers
Collision reaction not working 2 Answers