For my pinball game, I am having troubles with the movement of the plunger-looking thing (let’s call it plunger for the sake of simplicity) where they are position on both sides of the pinball board.
How do I get the plunger to spring forward by a certain amount of distance then stop at that distance?
I’ve used the MovePosition function but the plunger keeps moving onward without stopping.
I am not a programming expert, but here’s my script:
public class Plunge : MonoBehaviour {
public Rigidbody rb;
Vector3 startPos;
void Start()
{
rb = GetComponent<Rigidbody>();
startPos = rb.position;
}
void FixedUpdate()
{
rb.MovePosition(rb.position + Vector3.left * Time.deltaTime); // move the rigid body object to the left at 1 Unity unit per second.
if (Vector3.Distance(rb.position, startPos) == 5) // when the distance between the updated position and start position of the rigid body object is 5
{
rb.velocity = Vector3.zero; // halt the rigid body.
}
}
}
Some information on the two props.
For the ball:
I’ve created it straight from Unity.
Has a rigid body w/o gravity since there are gravity points created in the scene.
Interpolation is set to interpolate.
Collision Detection is set to Continuous Dynamic.
For the plunger:
I’ve exported it straight from 3Ds max in FBX format.
Has a rigid body w/o gravity.
Interpolation is set to interpolate.
Collision Detection is set to Continuous Dynamic.
For the plunger not sure if rigidbody is necessary with these settings enabled.
You are going to want to move the rigidbody using rb.AddForce! At least that is how I would do it. Also to lock it down the last element of the RigidBody component is Constraints; You are going to have to freeze the proper Pos/Rots so it doesn’t fly across the game view!
Which rigid body are you referring to? The ball or the plunger.
If you’re telling me to freeze the Pos and Rot of the ball then there maybe a potential problem. Cuz I’m planning on putting up a ramp in later levels.
I appreciate your 2 cents I’ll check out AddForce function.
To add on to what unity noob said,
Add the rigidbody to the “plunger” and the ball.
As far as making sure it doesnt keep spinning, use Mathf.Clamp to clamp its rotation at a defined min and max.
My teammate who is more of a programmer helped me by doing this script, but the “plunger” is not behaving the way I expect it to though it’s getting there.
The plunger manages to plunge forward and retract but the distance it plunges forward at is inconsistent and I believe it’s due to the fact that I’ve disabled “Is Kinematic”; however, if I enable it, the plunger doesn’t plunge forward when the ball makes contact with it.
A traditional game-makers’ approach would be to skip the physics. Just move it and set the final speed when it leaves the plunger area. After all, you know exactly how you want it to move, and physics is clearly a pain.