Gravity to inside walls of tube?
Just a heads up, im a beginner trying to make a game thats a bit ambitious for my skill level so be easy on me.
Basically I have a tube of a certain length, a wall object at the back end, and a ball object. I want the ball to stick to the inside walls of the tunnel and move freely and bounce off the back wall and come back. Ive searched for a long time and the closest thing i could find that kinda worked was this:
public float wallGravity = -9.81f;
void OnCollisionStay(Collision col)
{
Vector3 n = Vector3.zero;
foreach (ContactPoint C in
col.contacts)
n += C.normal;
n.Normalize();
Physics.gravity = -n * wallGravity;
}
Not exactly sure how it works but it acts crazy and doesnt really work well. Also it sticks itself to the back wall when it hits instead of bouncing off (i have bouncy physics material on back wall). So basically im looking for suggestions on a different way to stick the ball to the tunnel but not the back wall. Ive heard raycasting would work, but i know jack about that. If thats the best course, ill gladly learn about it. Anything would be helpful!
Answer by Semystic · Dec 19, 2020 at 03:35 AM
For those wondering, i found something that works much better. Could use some tweeking but its great. It rotates around the z axis of the tube rather than trying to force it to the inside walls. It runs a lot smoother too.
transform.RotateAround(tube.transform.position, Vector3.forward, 0);
Answer by xxmariofer · Nov 17, 2020 at 01:37 PM
the easiest solution is to add a tag to the backwall and inside the collisionevent check if its colliding with the wall
void OnCollisionStay(Collision col)
{
if(col.gameObject.tag == "BackWall") return;
Vector3 n = Vector3.zero;
foreach (ContactPoint C in
col.contacts)
n += C.normal;
n.Normalize();
Physics.gravity = -n * wallGravity;
}
Okay that part works, thank you. However the gravity part of the script is still garbage and doesnt work well. The ball seems to propel itself around the tube, but thats after it freaks out and starts flying around bouncing off the walls a few times. Do you have a better solution to that problem?
So i tried something else that seems to work much much better, but it seems to be pulling towards the back wall at all times.
public Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "backWall") return;
ContactPoint contact = collision.GetContact(0);
Vector3 position = contact.point;
rb.AddForce(position);
}
Any help would be appreciated!
Without seeing the project is hard to tell, but i would try disabling gravity on collision enter and reenabling it on collision exit in case thats the force pulling towards the back
Your answer
Follow this Question
Related Questions
My ball fall throw the ground ? 0 Answers
Physics for ball on an incline: rolling up a hill if half way up 1 Answer
Position Ball 2 Answers
Gravity not working 3 Answers
change gravity 1 Answer