stop the ball from moving after button is pressed
Hi, I'm trying to make a pachinko styled game and I want to make the ball drop by pressing space. Before pressing space I want to be able to choose where I drop the ball. But after I pressed space I can still move the ball. I tried using rigidbody.contriants but since I'm pretty new to unity I don't really know how to use it properly. Here is the code I have so far.
void Awake()
{
ballRb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
MoveBall();
if (Input.GetKeyDown(KeyCode.Space))
{
ballRb.useGravity = true;
ballRb.constraints = RigidbodyConstraints.FreezePositionX | RigidbodyConstraints.FreezePositionZ;
}
}
void MoveBall()
{
verticalInput = Input.GetAxis("Vertical");
horizontalInput = Input.GetAxis("Horizontal");
transform.Translate(Vector3.forward * Time.deltaTime * speed * verticalInput);
transform.Translate(Vector3.right * Time.deltaTime * speed * horizontalInput);
}
Answer by Tulula · Mar 17, 2021 at 04:43 PM
I am not the greatest myself at Unity or C# either but you could trying using a bool and check it before you call Move(). By defauly isDropped will be set to false and the if statement checks to see if isDropped is false before calling Move(), then change isDropped to true when you press space.
If false, then Move. Hope it helps.
bool isDropped;
void Awake()
{
ballRb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
if (!isDropped)
MoveBall();
if (Input.GetKeyDown(KeyCode.Space))
{
isDropped = true;
ballRb.useGravity = true;
ballRb.constraints = RigidbodyConstraints.FreezePositionX | RigidbodyConstraints.FreezePositionZ;
}
}
void MoveBall()
{
verticalInput = Input.GetAxis("Vertical");
horizontalInput = Input.GetAxis("Horizontal");
transform.Translate(Vector3.forward * Time.deltaTime * speed * verticalInput);
transform.Translate(Vector3.right * Time.deltaTime * speed * horizontalInput);
}
Hi Tulula,
That seems to work as I wanted it to, I just had to remove the ballRb.contraints since I want to ball to bounce off some obstacles, but the player can no longer move the ball when it's dropped. Thanks a lot
Your answer
![](https://koobas.hobune.stream/wayback/20220613030837im_/https://answers.unity.com/themes/thub/images/avi.jpg)